开发者

Rails - Associations - Automatically setting an association_id for a model which has 2 belongs_to

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 ti开发者_如何学JAVAme 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.


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")


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜