问题 has_many通过其他属性


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

谢谢。 Neelesh


4434
2018-03-19 17:43


起源

比如什么附加参数? - thenengah
我有一个模型帖子,一个连接模型PostTag和一个模型标签。我想指定谁为帖子创建了相关标签。 - Neelesh
@Codeglot关联模型本身可能具有超出两个链接对象的id的其他属性。 - William Denniss


答案:


这篇博文有完美的解决方案: 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 如果尚未保存模型,则必须使用,否则可以省略。


11
2017-10-22 15:50





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

1
2018-03-19 18:08



做标签时怎么样<< new_tag? - Neelesh


好吧,我处于类似的情况,我希望有一个连接表加入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。但它会自动生成模型。


1
2017-07-31 23:16





这里遇到了同样的问题。找不到任何教程如何让它在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
2017-07-12 08:28



看起来它会工作,但有一个更简洁的方式,看到我的答案:) - William Denniss