Joe Essey Joe Essey - 1 year ago 71
Ruby Question

Rails - How to use hidden field on form to pass a value of an object related to the one created on a form?

I am trying to pass an

from a form that creates a
from a
. Device
has_many rfids
. The
already exists in the db.

Here is the code from the form:

<th>RFID Tag #</th>
<%= f.label(:@passed_rfid_tag, @passed_rfid_tag) %>
<%= f.hidden_field :rfid_tag, :value => @passed_rfid_tag %>

Here is the code from the devices_controller:

def create
@cabinet = Cabinet.find(params[:device][:cabinet_id])
@device = Device.create(params[:device])
@device.rfids << Rfid.where('rfid_tag' => params[:rfid_tag]).first
@device.row_id = @cabinet.row_id

I get the following error because
is not an attribute of
. It is an attribute of

Can't mass-assign protected attributes: rfid_tag

app/controllers/devices_controller.rb:182:in `create'


Answer Source

The mass-assign error is happening because you are passing :rfid_tag as part of the params[:device] attribute hash.

In your example code, the :rfid_tag field needs to be provided using the hidden_field_tag form helper. This will keep it from being included in the params[:device] hash.

  <th>RFID Tag #</th>
    <%= label_tag 'rfid_tag', 'RFID Tag' %>
    <%= hidden_field_tag 'rfid_tag', @passed_rfid_tag %>

You can then access it via params[:rfid_tag]. Your create method should still work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download