【问题标题】:has_many through additional attributeshas_many 通过附加属性
【发布时间】:2011-07-18 20:01:28
【问题描述】:

我们如何通过关联在has_many中设置额外的参数?

谢谢。 尼利什

【问题讨论】:

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

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


【解决方案1】:
has_many :tags, :through => :post_tags, :conditions => ['tag.owner_id = ?' @owner.id]

【讨论】:

  • 打标签的时候怎么办
【解决方案2】:

这里遇到了同样的问题。找不到任何教程如何使其在 Rails 3 中即时工作。 但是你仍然可以通过 join 模型本身得到你想要的。

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

很丑,但这对我有用。

【讨论】:

  • 看起来可行,但有更简洁的方法,请参阅我的回答 :)
【解决方案3】:

这篇博文有完美解决方案: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 &lt;&lt; current_user

但是,要设置附加参数(在此示例中为 is_admin),而不是自动附加到数组的方式,您可以手动进行,如下所示:

product.save &amp;&amp; product.collaborators.create(:user =&gt; current_user, :is_admin =&gt; true)

这种方法允许您在保存时设置附加参数。注意。如果模型尚未保存,product.save 是必须的,否则可以省略。

【讨论】:

    【解决方案4】:

    嗯,我遇到了类似的情况,我想要一个连接 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。但它会自动生成模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 2015-08-22
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多