Rails / Ruby - 使用从另一个页面传递的数据预填充表单

时间:2013-03-14 13:38:08

标签: ruby-on-rails ruby

device部分rfid页面导航到view/cabinet/show表单时,如何获取值以预填充新的device表单? rfid has_one <%= link_to "Create New Device (non-functional)", new_device_path({:id => @rfid.id, cabinet_id: @cabinet.id}), :class => "btn btn-primary" %>

来自cabinet / show的链接:

devices_controller

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 ,当传递0或2个参数时,我希望创建方法有效:

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> 的cabinet_id和rfid部分:

{{1}}

谢谢。

2 个答案:

答案 0 :(得分:13)

如果你有:

<%= link_to "Create New Device (non-functional)", new_device_path({:id => @rfid.id, :cabinet_id => @cabinet.id}), :class => "btn btn-primary" %>

您可以使用以下方式预填充rfidcabinet_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] %>

请注意,您的params键必须与传递到link_to标记中的哈希值的值匹配。

答案 1 :(得分:4)

@ 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 %>

这样,如果params[:cabinet_id]不存在,@device.cabinet_id(现有值)将会持续存在。