我使用Ruby On Rails 5并有2个表:
1)包含shelfmark,harddisk_id
列的表档案2)具有列标签,容量
的表硬盘我有一个看起来像这样的存档表单(app / views / archives / _form.html.erb)
<%= form_with(model: archive, local: true) do |form| %>
<div class="field">
<%= form.label :shelfmark %><br />
<%= form.text_field :shelfmark %>
</div>
<%= form.fields_for :harddisk do |harddisk_fields| %>
<div class="field">
<%= harddisk_fields.label "Harddisk capacity" %><br />
<%= harddisk_fields.text_field :capacity %><br />
</div>
<div class="field">
<%= form.label "Harddisk Label" %><br />
<%= form.select :harddisk_id, Harddisk.order(label: :asc).collect {|a| [ a.label, a.id ] } %>
</div>
<% end %>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
在archives_controller.rb中,默认的CRUD方法包含以下代码段:
def archive_params
params.require(:archive)
.permit(:id, :shelfmark, :harddisk_id, harddisk_attributes: [:id, :capacity, :label])
end
当我从下拉列表中选择硬盘标签并单击“保存”时,我收到“成功”消息,但硬盘标签字段未更新。
在Rails服务器控制台上,我可以看到消息:
“未经许可的参数:: harddisk_attributes,:harddisk_id”
我确实已经在archives_controller中允许这些属性,或者我是否也必须在其他地方允许它? 我错过了什么?
app / controllers / archives_controller.rb中的:
def edit
end
def update
respond_to do |format|
if @archive.update(archive_params)
format.html { redirect_to @archive, notice: 'Archive entry was successfully updated.' }
format.json { render :show, status: :ok, location: @archive }
else
format.html { render :edit }
format.json { render json: @archive.errors, status: :unprocessable_entity }
end
end
end
Rails服务器日志:
Started PATCH "/archives/1" for ::1 at 2018-02-08 15:44:09 +0100
Processing by ImagecapturingsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"TfThFrCaA34qi3YliuGVliaaifCBk2KxRXlvA0UMEM2evFUe7M8ODwY5U/FEimNz+NXqdqr+HSKbU6sLRoSVBw==", "archive"=>{"shelfmark"=>"csg-0070 foo", "harddisk_attributes"=>{"capacity"=>"932", "id"=>"1"}, "harddisk_id"=>"135"}, "commit"=>"Update Archive", "id"=>"1"}
Archive Load (31.4ms) SELECT `archive`.* FROM `archive` WHERE `archive`.`id` = 1 LIMIT 1
Unpermitted parameters: :harddisk_attributes, :harddisk_id
(0.5ms) BEGIN
Harddisk Load (0.5ms) SELECT `harddisks`.* FROM `harddisks` WHERE `harddisks`.`id` = 1 LIMIT 1
(0.6ms) COMMIT
Redirected to http://localhost:3001/archives/1
Completed 302 Found in 86ms (ActiveRecord: 33.0ms)
和我的模特:
class Archive < ApplicationRecord
belongs_to :harddisk
accepts_nested_attributes_for :harddisk
end
class Harddisk < ApplicationRecord
has_many :manuscripts, through: :manuscripts_harddisks
end
从服务器日志中执行此代码段:
"archive"=>{
"shelfmark"=>"csg-0070 foo", "harddisk_attributes"=>{"capacity"=>"932", "id"=>"1"}, "harddisk_id"=>"135"}, "commit"=>"Update Archive", "id"=>"1"}
表示从harddisk_id:135和id:1的转换出错?