如何通过关联防止rails has_many出现“未知列”错误

时间:2016-05-31 20:17:08

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

尝试重构rails 4中的has_and_belongs_to_many关联,以便添加额外的列,但我正在为自引用has_many_through而苦苦挣扎。

项目可以包含许多组件。组件实际上只是项目,因此可以拥有自己的组件;

class Item < ActiveRecord::Base
  has_many :components, through: :component_items
  has_many :component_items
end

class Component < ActiveRecord::Base
  has_many :items, through: :component_items
  has_many :component_items
  self.table_name ="Items"
end

class ComponentItem < ActiveRecord::Base
  has_many :items
  has_many :components
end

架构看起来像......

create_table "component_items", force: :cascade do |t|
  t.integer "item_id",      limit: 4, null: false
  t.integer "component_id", limit: 4, null: false
end

create_table "items", force: :cascade do |t|
  t.string   "sku",    limit: 255
  t.decimal  "height", precision: 6, scale: 2
  t.decimal  "width",  precision: 6, scale: 2
  t.decimal  "depth",  precision: 6, scale: 2
end

然后

i=Item.first
i.components

我明白了:

  

ActiveRecord :: StatementInvalid:Mysql2 ::错误:'on子句'中的未知列'items.component_item_id':SELECT items。* FROM items INNER JOIN component_items ON {{ 1}}。items = component_item_idcomponent_items WHERE idcomponent_items = 87675

我不需要列item_id,所以我在哪里错误地定义了它?那么,我如何让这种关联起作用呢?

1 个答案:

答案 0 :(得分:0)

您的错误出现是因为rails搜索表items中的列belongs_to,但您没有此列,我相信您应该在item中创建class Item < ActiveRecord::Base has_many :components, through: :component_items has_many :component_items end class Component < Item has_many :items, through: :component_items has_many :component_items end class ComponentItem < ActiveRecord::Base belongs_to :item belongs_to :component end 关系对它来说,但是它似乎你在模式和模型之间只有错误的实现,所以对于你定义的当前方案,我建议模型:

type

注意这需要items表中另一个名为<% count = 1 %> <% @runners.group_by(&:finish_time).each do |(time, runners)| %> <% place = count %> <% runners.each do |r| %> <tr> <td><%= r.id %></td> <td><%= r.name %></td> <td><%= time %></td> <td><%= place.ordinalize %></td> </tr> <% count += 1 %> <% end %> <% end %> 的字符串字段。