Neon_10
Neon_10

Reputation: 731

how to assign Post to User through user_id and author_id?

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

Answers (2)

Neon_10
Neon_10

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

Vrushali Pawar
Vrushali Pawar

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

Related Questions