我有两个型号-- Customer和Contractors。我已经设置了一个简单的应用程序,他们在activity上互动。现在,在它的结尾,我想让他们相互反馈。没什么复杂的,只有一个comment的数据库字段。
我想知道在这里应该有什么样的模型关联?
我试过了
class Customer
has_many :feedbacks
end
class Contractor
has_many :feedbacks
end
class Feedback
belongs_to :customer
belongs_to :contractor
end但这里的问题是找出谁评论了谁。
例如,如果我这样做了
customer = Customer.find(1)
contractor = Contractor.find(1)
customer.feedbacks.create(:comment => "Contractor 1 sucks", :contractor_id => 1)问题是,contractor.feedbacks和customer.feedbacks都可以访问它。我不知道现在是谁在评论谁。
任何指导都是值得感谢的。我是不是遗漏了什么?
谢谢
发布于 2013-05-26 02:33:14
实现这一点的方法是使用polymorphic associations。
这样,您就可以拥有一个commenter关系和一个commentable关系。
如下所示:
class Customer
has_many :feedbacks, as: commenter
has_many :feedbacks, as: commentable
end
class Contractor
has_many :feedbacks, as: commenter
has_many :feedbacks, as: commentable
end
class Feedback
belongs_to :commenter, polymorphic: true
belongs_to :commentable, polymorphic: true
end现在,Feedback将需要四个新列:
commentable_type:stringcommentable_id:integercommenter_type:stringcommenter_id:integer所有这四个都应该被索引,所以适当地编写您的迁移。type列将存储相关模型名称的字符串值("Customer“或"Contractor")。
所以你可以这样做:
@feedback = Feedback.find 3
@feedback.commenter
=> # Some Customer
@feedback.commentable
=> # Some Contractor反之亦然。您将构建如下所示:
@customer = Customer.find 1
@contractor = Contractor.find 1
@feedback = Feedback.new comment: "This is a great Contractor"
@feedback.commenter = @customer # You can reverse this for a contractor giving feedback to a customer
@feedback.commentable = @contractor
@feedback.save!https://stackoverflow.com/questions/16752605
复制相似问题