rohan kharvi
rohan kharvi

Reputation: 118

Association among three model

I have these models with association as follows

class User
  has_many :comments
  belongs_to :country
end

class Country
  has_many :users
  has_many :comments
end

class Comment
  belong_to :user
  belong_to :country
end

Comment has user_id and country_id as column name. User has country_id as column name.

Now if i write this code is console

User.first.comments.create :content=>"some content"

This would create a comment but country_id column of Comment would be null. I want country_id to be filled based on user_id How can i do this

Upvotes: 1

Views: 40

Answers (4)

Matt
Matt

Reputation: 14038

Will the comment always have the same country as the user? If so do you really need that relation at all? You could just infer the country of the comment from the country of the user that made it.

Class Comment
  delegate :country, to: :user
end

comment.country will then automatically return comment.user.country

Upvotes: 2

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3043

You can set country based on user with before_save or before_create callbacks. This could help you:

class User
  has_many :comments
  belongs_to :country
end

class Country
  has_many :users
  has_many :comments
end

class Comment
  belong_to :user
  belong_to :country

  before_create :set_country

  def set_country
    self.country_id = user.country_id if user 
  end
end

Upvotes: 2

Chakreshwar Sharma
Chakreshwar Sharma

Reputation: 2610

Try the below:

u = User.first
u.comments.create(content: "Some comment", country_id: u.country.id)

Upvotes: 1

dp7
dp7

Reputation: 6749

you have to explicitely pass the country_id:

@user = User.first
@user.comments.create(:content=>"some content", country_id: @user.country)

Upvotes: 1

Related Questions