开发者

Building an active record with associations to two belongs_to relationships

开发者 https://www.devze.com 2023-02-14 20:10 出处:网络
Going back to an example I had previously asked about, I\'ll try and make this question as simple as possible.

Going back to an example I had previously asked about, I'll try and make this question as simple as possible.

Supposed I have User and Document models.

A User has_many Documents and a Document belongs_to a User. This relationship works fine today.

I want to introduce an Edits model that belongs_to a Document and belongs_to a User. The User can be any user, not necessary the one who created the document. With this new model, the Document now has_many :edits and the User has_many :edits.

So far it would look like:

# user.rb
class User < ActiveRecord::Base
   has_many :edits
   has_many :documents
end

# document.rb
class Document < ActiveRecord::Base
   belongs_to :user
   has_many :edits
end

# edit.rb
class Edit < ActiveRecord::Base
   belongs_to :user
   belongs_to :document
end

When I create a Document through a User, the association between the User and Document are fine in both directions (user.documents and document.user)

Now when I want to create an Edit, the edit should be against a Document but should also be associated with the user who generated the edit (edit.user).

When I'm building this in my RSpec tests I'm struggling to get the associations correct using the "standard" association methods. If I do @user.edits.build({...}) it will associate the user in the returned Edit object, but not the Document. Likewise when I do @document.edits.build({...}) it will associate the Document but not the User.

I supposed I could expose the user_id and post_id in the attr_accessible declaration but won't this but I fear this is not a best way of doing this. I开发者_如何学Go have no real reason to fear other than the attributes are now accessible through mass assignment (from what I understand).

Am I going about this the wrong way or is there a better way to create and test all the associations?


class User < ActiveRecord::Base
   has_many :edits, :through => :documents
   has_many :documents
end
0

精彩评论

暂无评论...
验证码 换一张
取 消