gpt4 book ai didi

ruby-on-rails - rails : Assign extra columns in HABTM join model

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:35 25 4
gpt4 key购买 nike

我不知道为什么我找不到任何东西这似乎是一个非常基本的问题。假设我有类似的东西

class Category < ActiveRecord::Base
has_many :categorizations
has_many :items, :through => :categorizations
end

class Item < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
end

class Categorization < ActiveRecord::Base
attr_accessible :some_field
belongs_to :category
belongs_to :item
end

和相关的迁移。然后可以做

item1=Item.new()
item2=Item.new()
foo=Category.new()
foo.items=[ item1, item2 ]

,对吧?那么,如何获得将 foo 链接到 item1 和 item2 的分类以设置 :some_field 的值?

最佳答案

如果你想添加额外的东西,你不能使用快速 channel 。我现在无法测试它,但像这样的东西应该可以工作:

item1 = Item.new
item2 = Item.new

foo = Category.new
foo.categorizations.build(:some_field=>'ABC', :item=>item1)
foo.categorizations.build(:some_field=>'XYZ', :item=>item2)

更新:

此外:如果您需要显示来自Categorization 的额外数据,您不能使用@category.items:

<h1><%= @category.name %></h1>

<% @category.categorizations.each do |categorization| %>
<h2><%= categorization.item.name %></h2>

<p>My extra information: <%= categorization.some_field %></p>
<% end %>

关于ruby-on-rails - rails : Assign extra columns in HABTM join model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11639660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com