我目前有一个posts模型,其中有一个列。我希望在某些类别中显示所有的帖子。
点击“技术”类链接-加载所有以苹果为分类的帖子。
无法在堆栈溢出上找到任何东西,但我可能找错了东西。任何帮助都将是辉煌的和感激的!
谢谢
发布于 2015-03-20 19:00:34
Post.where(category: 'Animals')
将返回所有具有指定类别的员额。
至于问题下的评论-是的,你可以受益于拥有额外的模型Category,因为post可以有更多,而不仅仅是一个类别。
您将将该关系定义为以下内容之一:
has_and_belongs_to_many :categories # post.rb has_and_belongs_to_many :posts # category.rbpost.rb
has_many :categories_posts
has_many :categories, through: :categories_postscategory.rb
has_many :categories_posts
has_many :posts, through: :categories_postscategories_posts.rb
belongs_to :category
belongs_to :post编辑
要将选择类别(Ies)添加到表单中,请向其添加以下内容(假设Category具有name属性):
<%= f.select :categories, Category.pluck(:id, :name), {}, multiple: true %>还不要忘记在允许的params (posts_controller.rb)中列出类别:
def post_params
params.require(:post).permit(:attr1, :attr2, category_ids: [])
end发布于 2015-03-20 19:04:14
在post.rb模型中,添加一个作用域
scope :animals, -> { where(category: 'Animals') }然后,在控制器中,只需调用:
Post.all.animalshttps://stackoverflow.com/questions/29173482
复制相似问题