我在rails 4上。假设我有三个模型;房屋、颜色和房屋着色。
class House < ActiveRecord::Base
has_many :house_colorings
has_many :colors, through: :house_colorings
accepts_nested_attributes_for :house_colorings, allow_destroy: true
end
class Color < ActiveRecord::Base
has_many :house_colorings
has_many :houses, through: :house_colorings
end
class HouseColoring < ActiveRecord::Base
belongs_to :house
belongs_to :color
end
我家控制器
class HousesController < ApplicationController
before_action :set_house
...
def new
@house = House.new
@house.house_colorings.build
end
def create
@house = House.create(house_params)
if @house.save
redirect_to @house
else
render 'new'
end
end
def edit
#Gets @house from set_house
end
def update
if @house.update(house_params)
redirect_to @house
else
render 'edit'
end
end
...
private
def set_house
@house = House.find(params[:id])
end
def house_params
params.require(:house).permit(:some_parameters, house_coloring_attributes: [:color_id, :some_other_params])
end
end
在创建新房子时,我的数据库中有一个颜色列表可供选择,而房子可以有多种颜色。当我去创建一个新房子时,我选择一种颜色,它保存得很好。我遇到的问题是我编辑了我刚刚创建的房子并决定更改颜色,它添加了一个新的 house_color 记录而不是更改我已经拥有的那个。
这是我的新房子和编辑的 _form.html.erb 部分
<%= form_for @house do |f| %>
<%= f.fields_for :house_colorings do |c| %>
....
<%= c.collection_select :color_id, Color.all, :id, :name, {include_blank: "Select color"} %>
<% end %>
<% end %>
为什么会这样?我需要更改什么才能更改/更新我的 house_coloring 而不是创建新记录?谢谢。
编辑:
这是我尝试更新房屋时发生的更新日志
Started PATCH "/MY_PATH/houses/16" for 127.0.0.1 at 2013-10-24 10:33:13 -0700
Processing by HousesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"sfdj43ksdkjsd3434fmskwec=", "house"=>{"name"=>"house", "house_colorings_attributes"=>{"0"=>{"color_id"=>"2", "id"=>"65"}, "1"=>{"color_id"=>"3", "id"=>"66"}, "2"=>{"color_id"=>"1", "id"=>"67"}}}, "commit"=>"Update House", "id"=>"16"}
[1m[36mHouse Load (0.1ms)[0m [1mSELECT "houses".* FROM "houses" WHERE "houses"."id" = ? LIMIT 1[0m [["id", "16"]]
Unpermitted parameters: id
Unpermitted parameters: id
Unpermitted parameters: id
[1m[35m (0.1ms)[0m begin transaction
[1m[36mSQL (1.0ms)[0m [1mINSERT INTO "house_colorings" ("house_id", "created_at", "color_id", "updated_at") VALUES (?, ?, ?, ?, ?)[0m [["house_id", 16], ["created_at", Thu, 24 Oct 2013 17:33:13 UTC +00:00], ["color_id", 2], ["updated_at", Thu, 24 Oct 2013 17:33:13 UTC +00:00]]
[1m[35mSQL (0.3ms)[0m INSERT INTO "house_colorings" ("house_id", "created_at", "color_id", "updated_at") VALUES (?, ?, ?, ?, ?) [["house_id", 16], ["created_at", Thu, 24 Oct 2013 17:33:13 UTC +00:00], ["color_id", 3], ["updated_at", Thu, 24 Oct 2013 17:33:13 UTC +00:00]]
[1m[36mSQL (0.1ms)[0m [1mINSERT INTO "house_colorings" ("house_id", "created_at", "color_id", "updated_at") VALUES (?, ?, ?, ?, ?)[0m [["house_id", 16], ["created_at", Thu, 24 Oct 2013 17:33:13 UTC +00:00], ["color_id", 1], ["updated_at", Thu, 24 Oct 2013 17:33:13 UTC +00:00]]
[1m[35m (10.5ms)[0m commit transaction
Redirected to http://localhost:3000/houses/16
Completed 302 Found in 24ms (ActiveRecord: 12.5ms)