views:

61

answers:

2

I have 3 models

class User < ...
  belongs_to :language
  has_many :posts
end

class Post < ...
  belongs_to :user
  belongs_to :language
end

class Language < ...
  has_many :users
  has_many :posts
end

Im going to be creating lots of posts via users and at the same time I have to also specify the language the post was written in, which is always the language associatd with the user i.e.

@user.posts.create(:text => "blah", :language_id => @user.language_id)

That's fine but the way I set the language doesn't sit well with me. The language will always be that of the users so is there a 'best-practice' way of doing this?

I know a little about callbacks and association extensions but not sure of any pitfalls.

+1  A: 

I would just make a create_post function in the user model:

def create_post(text)
  posts.create(:text => text, :language_id => language_id)
end

then just call it where ever you need.

Tony Fontenot
+3  A: 

Yes, there is a 'good practice' way involving callbacks.

class Post
  before_validation_on_create :set_language

  protected
  def set_language
    self.language ||= self.user.language if self.user
  end

end

Then, you can

@user.posts.create(:text => "blah")

or

post.create(:text => "fewf")
Vlad Zloteanu
excellent thats brilliant.
adam