Ruby on rails 在RubyonRails中,如何列出所有具有特定值的对象?
我正在构建一个页面,该页面将列出所有包含category_id值为“1”的模型,下面是该页面的代码片段Ruby on rails 在RubyonRails中,如何列出所有具有特定值的对象?,ruby-on-rails,ruby,database,ruby-on-rails-3,rails-activerecord,Ruby On Rails,Ruby,Database,Ruby On Rails 3,Rails Activerecord,我正在构建一个页面,该页面将列出所有包含category_id值为“1”的模型,下面是该页面的代码片段 <h1>Discover the best of Games</h1> <p>These are games we have featured and awarded</p> <% @posts.find_by(category_id: 1) do |post| %> <h2> <%= link_to p
<h1>Discover the best of Games</h1>
<p>These are games we have featured and awarded</p>
<% @posts.find_by(category_id: 1) do |post| %>
<h2>
<%= link_to post.title, post %>
</h2>
<% end %>
Posts\U控制器(全部)
class PostsController
任何帮助都将非常感谢,因为我对Rails非常陌生,刚刚掌握了基本知识。谢谢。编辑:
Post.where(category_id: 1)
因此:
这将列出第1类内的所有员额。这可能比Post.where
更明确,此版本的优点是如果页面上有您想要显示的类别的信息,例如类别名称。那么您已经拥有了对象:
@category = Category.find(1)
@posts = @category.posts
<h1>Posts for <%= @category.name %></h1>
<% @posts.each do |post| %>
... you know the rest
@category=category.find(1)
@posts=@category.posts
职位
... 其余的你都知道
不管怎么说,希望这能让事情变得更清楚一点,它是如何组合和工作的。编辑:
Post.where(category_id: 1)
因此:
这将列出第1类内的所有员额。这可能比Post.where
更明确,此版本的优点是如果页面上有您想要显示的类别的信息,例如类别名称。那么您已经拥有了对象:
@category = Category.find(1)
@posts = @category.posts
<h1>Posts for <%= @category.name %></h1>
<% @posts.each do |post| %>
... you know the rest
@category=category.find(1)
@posts=@category.posts
职位
... 其余的你都知道
不管怎样,希望这能让事情变得更清楚,让大家知道它们是如何组合和工作的。你可以使用
加入协会
def index
@posts = Post.joins(:category).where('posts.category_id = ?', 1).order("posts.created_at DESC")
end
或者,如果您想避免N+1,可以使用includes
def index
@posts = Post.includes(:category).where('posts.category_id = ?', 1).order("posts.created_at DESC")
end
我希望这对您有所帮助。您可以使用加入协会
def index
@posts = Post.joins(:category).where('posts.category_id = ?', 1).order("posts.created_at DESC")
end
或者,如果您想避免N+1,可以使用includes
def index
@posts = Post.includes(:category).where('posts.category_id = ?', 1).order("posts.created_at DESC")
end
我希望这对你有帮助。嗯。。。我似乎得到了nil:nilclass的未定义方法'find_by_category_id'。是的,对不起,我会更新我的帖子来解释区别,但是使用where
。另外,请使用Post
而不要使用@posts
,因为前者引用ActiveRecord类,而后者则表示一个(可能是未实例化的)对象—您是救世主。非常感谢。嗯。。。我似乎得到了nil:nilclass的未定义方法'find_by_category_id'。是的,对不起,我会更新我的帖子来解释区别,但是使用where
。另外,请使用Post
而不要使用@posts
,因为前者引用ActiveRecord类,而后者则表示一个(可能是未实例化的)对象—您是救世主。非常感谢。请注意,find_by
是类方法,而不是实例方法。因此,您可以在类Post
上调用它,但不能在该类的实例变量上调用它。因此,您可以在类Post
上调用它,但不能在该类的实例变量上调用它。