has_many通过其他属性

时间:2011-03-19 17:43:13

标签: ruby-on-rails ruby-on-rails-3 has-many-through

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

感谢。 Neelesh

4 个答案:

答案 0 :(得分:12)

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

该解决方案是:手动创建“:through model”,而不是在附加到其所有者的数组时通过自动方式创建。

使用该博客文章中的示例。您的模型在哪里:

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 :(得分:1)

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

答案 2 :(得分: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。但它会自动生成模型。

答案 3 :(得分: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

非常难看,但这对我有用。

相关问题