2011-03-19 20 views
9

関連を介してhas_manyに追加のパラメータを設定するにはどうすればよいですか?追加の属性を介してhas_many

ありがとうございました。 Neelesh

+0

などの追加パラメータはありますか? – s84

+1

モデルポスト、結合モデルPostTag、モデルタグがあります。投稿の関連タグを誰が作成したのかを指定したい。 – Neelesh

+0

@Codeglotアソシエーションモデル自体には、2つのリンクされたオブジェクトのIDを超える追加の属性が潜在的に存在する可能性があります。 –

答えて

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

タグを実行するときはどうなりますか?<< new_tag? – Neelesh

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

それはうまくいくように見えますが、もっときれいな方法があります。私の答えを見てください:) –

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を。このアプローチは、あなたがすることができます

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

しかし、むしろ配列に追加の自動化された方法よりも、(この例is_adminで)追加の​​引数を設定するには、次のように手動でそれを行うことができます保存時に追加の引数を設定します。 NB。モデルがまだ保存されていない場合はproduct.saveが必要です。それ以外の場合は省略できます。

1

私は、3つのモデルを結合した結合テーブルを用意したいという同様の状況にありました。しかし、私は3番目のモデルIDを2番目のモデルから取得したかったのです。

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へのアクセスを持っていないだろうと思いました。しかし、自動的にモデルを生成します。

関連する問題