当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - How do I create a scope to find all objects in my class that `include?` a string on an attribute?

问题描述:

I have a Node object that has an attribute called cached_user_tag_list, that stores a comma separated list of email addresses as a string like this:

[3] pry(main)> n.cached_user_tag_list

=> "[email protected], [email protected]"

If I set a local variable to be one of those email addresses, I can use ruby's include? string method to find if a node contains that email address. Here is an illustration:

[6] pry(main)> g = "[email protected]"

=> "[email protected]"

[8] pry(main)> n.cached_user_tag_list.include? g

=> true

What I would like to do, is create a Scope on my Node class/model that will accept g and search against the column/attribute cached_user_tag_list for all the Nodes in my DB and return a collection or AR Relation of all of those Nodes that contain that email address stored in the variable g within their string at cached_user_tag_list.

How do I do this?

Edit 1

I tried Node.where('cached_user_tag_list.include?'(g)), but that didn't work.

网友答案:

If it's just plain old string column with comma separated values, you can do something like this:

scope :find_nodes_which_include, ->(email) { |email| where("cache_user_tag_list like ?", "%#{email}%") }

分享给朋友:
您可能感兴趣的文章:
随机阅读: