Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

ruby - How to return an array of clients with include?

A client has many different colored shirts: red, blue, pink etc. I want to pick out all clients with red shirts. How?

Shirts are stored like this:

c = Client.last
c.shirt #=> "red,blue,pink"

If the client had one colored shirt, I'd get the information like:

Client.where(shirt: "red")

But since a client will have many shirts, I need something like include?. The English would be: Give me all clients that has a red shirt. How do you write that?

c = Client.all
c.map do |m| m.shirt.include? "red" end #=> [0] true

I like to return an array of clients with red shirts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be able to find it with:

Client.where('shirt like ?', "%#{color}%")

The percentage sign (%) matches anything. So you are looking for all the clients whose shirt colors match

<ANYTHING>red<ANYTHING>

Now this works as long as search terms do not include each other. So if you have following colors

  • red
  • darkred
  • lightred

then searching for "%red%" will yield all three variants as result.

Depending on how you DB schema looks like and how many records you have, it might be easier if you have "ShirtColors" as separate entities and link them to clients.

UPDATE:

If you have cases as described above with "red", "darkred" and so on and you want to stick with the "short color as column" approach:

  • Add separator before, between and after the colors: ",red,blue,darkred,"
  • Search for:

    Client.where('shirt like ?', ",#{color},")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...