Rails - How to use a hidden field in a form to convey the value of the object associated with the created in the form?

I am trying to pass rfid_tag from a form that creates a device from hidden_field . The has_many rfids . rfid already exists in db.

Here is the code from the form:

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

Here is the code from device_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 @device.save 

I get the following error because rfid_tag not a device attribute. This is the rfid attribute:

 Can't mass-assign protected attributes: rfid_tag app/controllers/devices_controller.rb:182:in `create' 

Thanks.

+4
source share
2 answers

An array assignment error occurs because you pass :rfid_tag as part of the hash of the params[:device] attribute.

In your sample code, the :rfid_tag field should be provided using the hidden_field_tag form hidden_field_tag . This will prevent it from being included in the params[:device] hash.

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

Then you can access it via params[:rfid_tag] . Your create method should work.

+7
source

Do what Dan Reedy said and use the hidden_field_tag ​​file in your form.

I am worried about this line in the controller creation method:

 @device.rfids << Rfid.where('rfid_tag' => params[:rfid_tag]).first 

It’s good if your rfid also has many devices, so you have a lot of different relationships. If the rfid tag comes with just one device, although you may have to change it to something like:

 rfid = Rfid.where('rfid_tag' => params[:rfid_tag]).first rfid.device_id = @device.id rfid.save! 

And, of course, do not forget to handle cases when case_id or rfid_tag ​​are not found in the database, which you get from the params hash. He can never count on the input entered by the user to be valid or correspond to the real records, even if he is hidden from the fields.

+3
source

Source: https://habr.com/ru/post/1469350/


All Articles