Joe*_*sey 12 ruby ruby-on-rails
device当从rfid部分view/cabinet/show页面导航到新表单时,如何获取值以预填充新表单? devicehas_one rfid.
来自橱柜/展示的链接:
<%= link_to "Create New Device (non-functional)", new_device_path({:id => @rfid.id, cabinet_id: @cabinet.id}), :class => "btn btn-primary" %>
Run Code Online (Sandbox Code Playgroud)
的devices_controller,我想有create方法工作的时候是0或2 PARAMS传递:
def create(options)
if options[:cabinet_id] and options[:id]
@rfid = Rfid.find(params[:id])
@device = Device.new(params[:device])
@device.rfid = @rfid
@device.cabinet_id = :cabinet_id
else
@device = Device.new(params[:device])
@cabinet = Cabinet.find(params[:device][:cabinet_id])
@device.row_id = @cabinet.row_id
end
respond_to do |format|
if @device.save and @cabinet.refresh_capacity_used and @cabinet.refresh_consumption
format.html { redirect_to @device, notice: 'Device was successfully created.' }
format.json { render json: @device, status: :created, location: @device }
else
format.html { render action: "new" }
format.json { render json: @device.errors, status: :unprocessable_entity }
end
end
Run Code Online (Sandbox Code Playgroud)
结束
新的cabinet_id和rfid部分device/_form:
<tr>
<th>Cabinet</th>
<td><%= f.select :cabinet_id, options_from_collection_for_select(Cabinet.order(:name).all, "id", "name", @device.cabinet_id) %></td>
</tr>
<tr>
<th>RFID</th>
<td><%= f.text_field :rfid, :value => params[:rfid]%></td>
</tr>
Run Code Online (Sandbox Code Playgroud)
谢谢.
zea*_*soi 13
如果你有:
<%= link_to "Create New Device (non-functional)", new_device_path({:id => @rfid.id, :cabinet_id => @cabinet.id}), :class => "btn btn-primary" %>
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法预填充rfid和cabinet_id字段:
<%= f.select :cabinet_id, options_from_collection_for_select(Cabinet.order(:name).all, "id", "name", params[:cabinet_id]) %>
<%= f.text_field :rfid, :value => params[:id] %>
Run Code Online (Sandbox Code Playgroud)
请注意,params键必须与传递到link_to标记中哈希值的值匹配.
@zeantsoi发布的答案大都可以,但是它破坏了编辑功能。作为修复,我建议进行以下较小的修改:
<%= f.select :cabinet_id, options_from_collection_for_select(Cabinet.order(:name).all, "id", "name", params[:cabinet_id] || @device.cabinet_id) %>
<%= f.text_field :rfid, :value => params[:rfid] || @device.rfid %>
Run Code Online (Sandbox Code Playgroud)
这样,如果params[:cabinet_id]不存在,@device.cabinet_id(现有值)将持久存在。
| 归档时间: |
|
| 查看次数: |
13354 次 |
| 最近记录: |