rails map.resources with has_many :through doesn't work?

后端 未结 3 1519
北恋
北恋 2021-01-03 09:27

I\'ve got three (relevant) models, specified like this:

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
  has_many :comments_receiv         


        
3条回答
  •  执念已碎
    2021-01-03 10:16

    Although the syntax to deinfe resource and model relationship is similar, you shouldn't be fooled into thinking that a resource maps to a model. Read what David Black has to say.

    The problem you're having is with the routes you're generating. Using the nested syntax like so:

    map.resources :users do |user|
      user.resources :posts
      user.resources :comments
      user.resources :comments_received
    end
    

    And then running 'rake routes', gives me (amongst loads of other stuff!):

                           users GET /users                              {:action=>"index", :controller=>"users"}
                      user_posts GET /users/:user_id/posts               {:action=>"index", :controller=>"posts"}
                   user_comments GET /users/:user_id/comments            {:action=>"index", :controller=>"comments"}
    user_comments_received_index GET /users/:user_id/comments_received   {:action=>"index", :controller=>"comments_received"}
    

    So it appears that rails is adding _index to the end of the comments_received route. I'll admit I don't know why (something to do with clashing with the other comments route?) but it explains your problem.

    An nicer alternative might be to define a collection action on your comments resource, like so:

    map.resources :users do |user|
      user.resources :posts
      user.resources :comments, :collection => {:received => :get}
    end
    

    This will give you the following routes:

                     users GET /users                             {:action=>"index", :controller=>"users"}
                user_posts GET /users/:user_id/posts              {:action=>"index", :controller=>"posts"}
             user_comments GET /users/:user_id/comments           {:action=>"index", :controller=>"comments"} 
    received_user_comments GET /users/:user_id/comments/received  {:action=>"received", :controller=>"comments"}
    

    Note: the received action is now on the comments controller

提交回复
热议问题