我想设置一个表单,我可以在其中编辑一些嵌套对象并同时创建新对象。
这就是我到现在所得到的:
class Rate < ActiveRecord::Base
belongs_to :org_unit
validates_uniqueness_of :name
validates_presence_of :name, :tablename, :rate_order_no, :ratevalue
end
class OrgUnit < ActiveRecord::Base
has_many :rates
accepts_nested_attributes_for :rates
end
class OrgUnitsController < ApplicationController
before_action :set_org_unit, only: [:show, :edit]
def index
@org_units = OrgUnit.all
end
def show
end
def edit
end
def update
if @org_unit.update(org_unit_params)
redirect_to @org_unit, notice: 'Update successfull.'
else
render action: 'edit'
end
end
private
def set_org_unit
@org_unit = OrgUnit.find(params[:id])
@rates = @org_unit.rates
end
def org_unit_params
params.require(:org_unit).permit(
:rates_attributes => [:name, :tablename, :rate_order_no, :ratevalue]
)
end
端
#Organisation Units
get '/org_units/', :to => 'org_units#index', :as => 'org_units'
get '/org_units/:id', :to => 'org_units#show', :as => 'org_unit'
get '/org_units/:id/edit', :to => 'org_units#edit', :as => 'edit_org_unit'
put '/org_units/:id', :to => 'org_units#update'
patch '/org_units/:id', :to => 'org_units#update'
<%= simple_nested_form_for @org_unit do |f| %>
<table id="ratetable" class="display">
<thead>
<tr> <th>Rate Name</th> <th>Table</th> <th>Department</th> <th>Value</th> </tr>
</thead>
<tbody>
<%= f.simple_fields_for :rates, :wrapper => false do |ff| %>
<tr class="fields">
<td><%= ff.input :name, label: false, required: true %></td>
<td><%= ff.input :tablename, collection: ["Costs","Savings","CnQ"], label:false, required: true, prompt: "Select the table" %></td>
<td><%= ff.input :rate_order_no, collection: 1..19, label:false, required: true, prompt: "Select the row"%></td>
<td><%= ff.input :ratevalue, label: false, required: true %></td>
</tr>
<% end %>
</tbody>
</table>
<p><%= f.link_to_add "Add a rate", :rates, :data => { :target => "#ratetable" }, :class => "btn btn-default" %></p>
<br>
<br>
<%= f.submit "Save Rates", :class => "btn bnt-default" %>
<% end %>
现在,如果我单击提交按钮,则rails会占用每条填充行并创建一个具有org_unit_params属性的新速率。因此,旧的费率不会在我的数据库中多次更新。
我想要的是,如果他们改变并为其他人创建新记录,他会更新旧的记录。
它应该与create_or_update
有关,但我不能把它放在一起。
会感激每一个提示。
提前致谢并致以最诚挚的问候。
答案 0 :(得分:0)
好的,我必须在我允许的属性中添加:id:
def org_unit_params
params.require(:org_unit).permit(:id, :name,
rates_attributes: [:id, :name, :tablename, :rate_order_no, :ratevalue, :org_unit_id, :_destroy]
)
end
但这还不够:(所以我必须在我的fields_for中添加一个隐藏的输入字段:id,现在它可以工作:
<%= f.simple_fields_for :rates, :wrapper => false do |ff| %>
<tr class="fields">
<td><%= ff.input :name, label: false %></td>
<td><%= ff.input :tablename, collection: ["Costs","Savings","CnQ"], label:false, prompt: "Select the table" %></td>
<td><%= ff.input :rate_order_no, collection: 1..19, label:false, prompt: "Select the row"%></td>
<td><%= ff.input :ratevalue, label: false, required: true %></td>
<td><%= ff.link_to_remove "Remove", :class => "btn btn-default" %></td>
<%= ff.input :id, :as => :hidden %>
</tr>
<% end %>