has_many through additional attributes

后端 未结 4 715
温柔的废话
温柔的废话 2020-12-15 08:48

How do we set additional parameters in has_many through associations?

Thanks. Neelesh

4条回答
  •  太阳男子
    2020-12-15 08:49

    Got the same problem here. Can't find any tutorials how to make it work on-the-fly in Rails 3. But you can still get what you want through the join model itself.

    p = Post.new(:title => 'Post', :body => 'Lorem ipsum ...')
    t = Tag.new(:title => 'Tag')
    
    p.tags << t
    p.save   # saves post, tag and also add record to posttags table, but additional attribute is NULL now
    j = PostTag.find_by_post_id_and_tag_id(p,t)
    j.user_id = params[:user_id]
    j.save   # this finally saves additional attribute
    

    Pretty ugly but this works from me.

提交回复
热议问题