【问题标题】:Rails route for through association通过关联的 Rails 路线
【发布时间】:2013-08-24 10:37:22
【问题描述】:

我是 Rails 的新手,我正在创建一个博客网站,我需要一个帖子来拥有一个类别,最终结果 url 将是这样的 - foo.com/category(title)/post(标题)所以经过大量谷歌搜索,然后观看此 railscast http://railscasts.com/episodes/47-two-many-to-many。我有以下模型,但不知道路线应该是什么。

我现在应该使用类别的索引视图来显示所有帖子吗?

模型 - 分类

class Categorisations < ActiveRecord::Base
  attr_accessible :category_id, :product_id
end

型号 - 类别

class Category < ActiveRecord::Base
  attr_accessible :title, :image
  has_many :categorisations
  has_many :posts, :through => :categorisations
end

模型 - 帖子

class Post < ActiveRecord::Base
attr_accessible :body, :is_verified, :publish_date, :title, :url, :tag_list, :image, :category_id
  has_many :categorisations
  has_many :categories, :through => :categorisations
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 blogs


    【解决方案1】:
    resources :categories do
      resources :posts
    end
    

    将为您提供 /category/1/post/1 的资源

    http://guides.rubyonrails.org/routing.html#nested-resources

    查看 railscast 的 ulr 中的标题

    编辑:

    要回答您之前的评论,我建议您这样做: @category = Category.find(params[:id]) @posts = @category.posts

    【讨论】:

    • 太好了,我需要在我的类别索引控制器中添加什么来显示该类别的所有帖子?我认为这是不正确的@posts = categories.posts
    • 您找到解决方案了吗?
    • No :( 我找到了 question 这正是我想要的,但我完全迷失了创建控制器和视图,因为正常的 Rails 方式是通过过滤,所以 URL 会显示类似foo.com/?category=2 但这对用户或谷歌来说并不好。你能指出我的任何方向或你推荐的任何资源吗?
    • 用应该可以工作的控制器代码更新了我的答案,你也看过我在我的答案中链接的 railscast 吗?
    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 2013-04-13
    相关资源
    最近更新 更多