开发者

Rails - Efficient way of finding entries with specific value in model

So I am trying to find all entries in my table that have a specific value in a particular column. The only way I can think off to do this is to look at each entry and see if it has the value but I was hoping there would be a more efficient solution - this gets unwieldy once you have a sizable database.

Does anyone have a better idea?

Update - I am creating an HTML table and I want to populate the table with all the entries in my m开发者_如何学Pythonodel that have a certain value in a particular column. I am trying to do:

<%= render @users.where("column_name = 'value'") %>

as the answer below recommends but I get "undefined method `where' for nil:NilClass" error.

Update 2 - I am not sure why @users would be nil but I will try to figure that out later. For now, I tried

<% @user_message = User.where("column_name = 'value'") %>
<%= render @user_message %>

but it doesn't show any entries at all.

Update 3 - When I do, User.all in rails console, I get all the users so I know the data is there. However, when I do User.where("column_name = 'value'"), I get an empty array. I double checked the column name and value to make sure that the data was present.

Update 4 - Fixed! - I'm not sure why it didn't work in rails console but I got it to work in the site. I called my partial _user_message.html.erb. Apparently it still needs to be called _user.html.erb. Thanks for the help everyone!


Sounds like you want to do a where query, i.e.

@records = Model.where(:some_column => some_value)

Rails has excellent documentation, I suggest you take a look at the ActiveRecord Query guide:

http://guides.rubyonrails.org/active_record_querying.html

ian.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜