Reputation: 731
I have a table users. they can post records in different users profiles, so for every post I have user_id (in whose profile a post was written) and autor_id (who wrote the post). Please could you help me - which relations should be to connect posts model with users twice? Now I have such code:
user.rb
has_many :posts, :dependent => :destroy
post.rb
belongs_to :user
has_one :author, :class_name => "User"
it does not let me call @post.author.name, as I see I connected it wrong to the users model. Please could you help me?
Upvotes: 1
Views: 1548
Reputation: 731
finally I resolved the problem:
user.rb
has_many :posts, :class_name => "Post", :foreign_key => "user_id"
has_many :records, :class_name => "Post", :foreign_key => "author_id"
post.rb
belongs_to :user, :class_name => "User", :foreign_key => 'user_id'
belongs_to :author, :class_name => "User", :foreign_key => 'author_id'
authors put records, users get posts written by authors. Thank you, @test
Upvotes: 1
Reputation: 3803
Your associations are wrong..they should be like this
belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
And now you can call it as
@post.author.name
There is a difference between belongs_to
and has_one
and that is you should define belongs_to when that table is containing foreign key.
Upvotes: 3