0

问题是:给定两个模型 A 和 B 在 HABTM 关联中,当我创建 A 的新实例时,如何指示 Rails 不写入 A、B 和 A_B,而只写入 A 和 A_B?

所以,更准确地说:我有两个相关的模型:气球和颜色

class Balloon < ActiveRecord::Base
  has_and_belongs_to_many :colors
end 
class Color < ActiveRecord::Base
  has_and_belongs_to_many :balloons
end

_form.html.haml 包含:

  .field
    = f.label :color
    - Color.all.each{|c|
    = check_box_tag("color[]", c.name)
    = c.name
    -}

和气球控制器:

  def create
    @balloon = Balloon.new(params[:balloon])
    params[:color].each do |col|
      @balloon.colors.build(:name=>col)
    end
    ....

保存时,表中有以下记录:

sqlite> select * from balloons;
1|b1
2|b2
3|b3
4|b4

sqlite> select * from colors;
1|red
2|green
3|red
4|red
5|red


sqlite> select * from balloons_colors;
1|1
1|2
2|3
3|4
4|5

问题是我不希望表 Colors 收到重复的记录,我希望负责关联的表 (balloons_colors) 每次添加气球时都会获得额外的记录。所以我想要类似的东西

sqlite> select * from colors;
1|red
2|green

sqlite> select * from balloons_colors;
1|1
1|2
2|1
3|1
4|1

编辑:添加架构:

sqlite> .schema balloons_colors 
CREATE TABLE "balloons_colors" ("balloon_id" integer, "color_id" integer); 

该表是由以下迁移创建的

class BalloonsHaveAndBelongToManyColors < ActiveRecord::Migration
  def self.up
    create_table :balloons_colors, :id => false do |t|
      t.references :balloon, :color
    end
  end
.....
end
4

1 回答 1

1

问题是你使用buildon @ballon.colors。Build 实例化一种新颜色,而不是找到一种颜色。向集合中添加成员通常是这样完成的:

@color = Color.find(params[:color_id]) 
@balloon.colors << @color

另一种方法是使用嵌套属性。

于 2013-03-15T14:04:57.893 回答