Rails - 查找模型中具有特定值的条目的有效方法

发布于 2024-11-10 05:42:20 字数 807 浏览 0 评论 0原文

因此,我试图查找表中特定列中具有特定值的所有条目。我能想到的唯一方法是查看每个条目,看看它是否具有价值,但我希望有一个更有效的解决方案 - 一旦你拥有一个相当大的数据库,这就会变得很笨拙。

有人有更好的主意吗?

更新 - 我正在创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陈甜 2024-11-17 05:42:20

听起来你想做一个where查询,即

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

Rails有很好的文档,我建议你看一下ActiveRecord查询指南:

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

ian。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文