how to assign Post to User through user_id and author_id?

1.5k views Asked by At

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?

2

There are 2 answers

1
Vrushali Pawar On BEST ANSWER

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.

0
Neon_10 On

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