用于Rails中的递归关联的嵌套资源

时间:2016-01-11 05:22:23

标签: ruby-on-rails database activerecord entity-relationship

在我的应用程序中,用户可以评价其他用户。 我定义了以下架构:

# feedback.rb
class Feedback < ActiveRecord::Base
  belongs_to :subject, class_name: 'User', foreign_key: 'subject_id'
  belongs_to :writer, class_name: 'User', foreign_key: 'writer_id'
end

# user.rb
class User < ActiveRecord::Base
   has_many :feedbacks, class_name: 'Feedback', foreign_key: 'subject_id'
   has_many :written_feedback, class_name: 'Feedback', foreign_key: 'writer_id'
end

现在我必须定义路线,我不禁考虑嵌套或不考虑资源,如果是的话。

这是我尝试定义路线的方式,但我对此并不确定。 通过这种方式,我只能达到或给用户的反馈或用户写的反馈。

#routes
....
  resources :users, except: [:new, :edit] do 
    resources :feedbacks, except: [:new, :edit]
  end

这是构建此架构的最佳方式吗?

1 个答案:

答案 0 :(得分:0)

经过一些尝试,我决定扩展feedbacks_controller。

class FeedbacksController < ApplicationController
end

module Feedbacks
  class ReceivedFeedbacksController < FeedbacksController
  end
end


module Feedbacks
  class GivenFeedbacksController < FeedbacksController
  end
end


#routes
Rails.application.routes.draw do
    resources :given_feedbaks,
              only: [:index],
              controller: 'feedbacks/given_feedbacks'
    resources :received_feedbaks,
              only: [:index],
              controller: 'feedbacks/received_feedbaks'
  end
  resources :feedbacks, only: [:show, :create, :update, :destroy]
end