Thursday, April 21, 2011

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 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.

From stackoverflow
  • 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.

  • 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")
    
    adam : excellent thats brilliant.

0 comments:

Post a Comment