Rails - 查找模型中具有特定值的条目的有效方法
因此,我试图查找表中特定列中具有特定值的所有条目。我能想到的唯一方法是查看每个条目,看看它是否具有价值,但我希望有一个更有效的解决方案 - 一旦你拥有一个相当大的数据库,这就会变得很笨拙。
有人有更好的主意吗?
更新 - 我正在创建一个 HTML 表,我想用我的模型中在特定列中具有特定值的所有条目填充该表。我正在尝试这样做:
<%= render @users.where("column_name = 'value'") %>
正如下面的答案所建议的那样,但我收到“undefined method `where' for nil:NilClass”错误。
更新 2 - 我不确定为什么 @users 为零,但我稍后会尝试解决这个问题。现在,我尝试过
<% @user_message = User.where("column_name = 'value'") %>
<%= render @user_message %>
,但它根本不显示任何条目。
更新 3 - 当我在 Rails 控制台中执行 User.all 时,我得到了所有用户,所以我知道数据在那里。但是,当我执行 User.where("column_name = 'value'") 时,我得到一个空数组。我仔细检查了列名称和值以确保数据存在。
更新 4 - 已修复! - 我不确定为什么它在 Rails 控制台中不起作用,但我让它在站点中工作。我将我的部分命名为 _user_message.html.erb。显然它仍然需要被称为_user.html.erb。感谢大家的帮助!
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 model 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来你想做一个where查询,即
Rails有很好的文档,我建议你看一下ActiveRecord查询指南:
http://guides.rubyonrails.org/active_record_querying.html
ian。
Sounds like you want to do a where query, i.e.
Rails has excellent documentation, I suggest you take a look at the ActiveRecord Query guide:
http://guides.rubyonrails.org/active_record_querying.html
ian.