【发布时间】:2014-07-16 12:56:25
【问题描述】:
我想设置一个表单,我可以在其中编辑一些嵌套对象并同时创建新对象。
这就是我到目前为止得到的:
型号:
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有关,但我不能把它放在一起。
感谢每一个提示。
在此先致谢并致以最诚挚的问候。
【问题讨论】:
-
好的,将 ':id' 添加到 'permitted attributes' 但它仍然无法正常工作。有人吗?
标签: ruby-on-rails-4 nested-forms