gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:41:14 25 4
gpt4 key购买 nike

view/cabinet/show 页面的 rfid 部分导航到新的 device 表单时,如何获取值以预填充新的 device 表单? 设备 has_one rfid

来自cabinet/show的链接:

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

devices_controller,我想让 create 方法在传递 0 或 2 个参数时起作用:

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

结束

device/_form的cabinet_id和rfid部分:

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

谢谢。

最佳答案

如果你有:

<%= 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 标记中的散列值相匹配。

关于ruby-on-rails - Rails/Ruby - 使用从另一个页面传递的数据预填充表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15410895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com