2011-03-19 91 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。但它會自動生成模型。