2011-03-19 197 views
9

我们如何通过关联在has_many中设置其他参数?has_many通过附加属性

谢谢。 Neelesh

+0

等附加参数是什么? – s84 2011-03-19 17:47:02

+1

我有一个模型帖子,一个连接模型PostTag和一个模型标签。我想指定谁为帖子创建了关联标签。 – Neelesh 2011-03-19 17:59:04

+0

@Codeglot关联模型本身可能具有超出两个链接对象的id的附加属性。 – 2012-10-22 15:53:43

回答

1
has_many :tags, :through => :post_tags, :conditions => ['tag.owner_id = ?' @owner.id] 
+3

什么时候做标签<< new_tag? – Neelesh 2011-03-20 04:01:55

0

在这里遇到同样的问题。找不到任何教程如何使它在Rails 3中实时运行。 但是,仍然可以通过联接模型本身获得您想要的内容。

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 

很丑,但这是从我的作品。

+0

看起来像它会工作,但有一个更好的方法,看到我的回答:) – 2012-10-22 15:51:35

10

本博客文章有完美的解决方案:http://www.tweetegy.com/2011/02/setting-join-table-attribute-has_many-through-association-in-rails-activerecord/

这种解决方案:创建“:通过模式”手动,而不是通过当你追加到其拥有者的阵列的自动方式。

使用该博客文章中的示例。你的型号是:

class Product < ActiveRecord::Base 
    has_many :collaborators 
    has_many :users, :through => :collaborators 
end 

class User < ActiveRecord::Base 
    has_many :collaborators 
    has_many :products, :through => :collaborators 
end 

class Collaborator < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :user 
end 

以前你可能已经去了:product.collaborators << current_user

然而,手动设置额外的参数(在该示例is_admin),而不是附加到阵列的自动方式,则可以做到这一点,如:

product.save && product.collaborators.create(:user => current_user, :is_admin => true)

这种方法允许你在保存时设置附加参数。 NB。如果模型尚未保存,则需要product.save,否则可以省略。

1

那么我是在类似的情况下,我想有一个连接表,加入了3个模型。但我想要从第二个模型中获得第三个模型ID。

class Ingredient < ActiveRecord::Base 

end 

class Person < ActiveRecord::Base 
    has_many :food 
    has_many :ingredients_food_person 
    has_many :ingredients, through: :ingredients_food_person 
end 

class Food 
    belongs_to :person 
    has_many :ingredient_food_person 
    has_many :ingredients, through: :ingredients_food_person 

    before_save do 
    ingredients_food_person.each { |ifp| ifp.person_id = person_id } 
    end 
end 

class IngredientFoodPerson < ActiveRecord::Base 
    belongs_to :ingredient 
    belongs_to :food 
    belongs_to :person 
end 

令人奇怪的是,你可以做这样的事情:

food = Food.new ingredients: [Ingredient.new, Ingredient.new] 
food.ingredients_food_person.size # => 2 
food.save 

起初我还以为是我救了之前,我不会有分配#ingredients后获得#ingredients_food_person。但它会自动生成模型。