0

How can I set a field of an object to a fixed value using a button or link in Rails? It seems like this should be a fairly basic procedure, but I haven't been successful with it. An example would be to set the parent_id of a product model to nil (related earlier question Update field through link_to in Rails). I have managed to achieve this through a form by leaving the text field empty:

<%= form_for @product do |f| %>    
    <%= f.label :parent_id %>
    <%= f.text_field :parent_id %>
    <%= f.submit "Update", class: "btn" %>  
<% end %>

But how can this be done without a text field, simply using a button, so that the parent_id is set to nil when the button is pressed? I have also tried to set the parent_id in a hidden field, but that doesn't work.

<%= form_for @product do |f| %>
   <%= f.hidden_field parent_id: nil %>
   <%= f.submit "Remove", class: "btn" %>
<% end %>

The controller looks like this for the edit/update actions.

products_controller.rb

def edit
   @product = Product.find_by_id(params[:id])    
end

def update
  if @product.update_attributes(params[:product])
    flash[:success] = "Product updated"
    redirect_to @product
  else
    render 'edit'
  end
end

Edit

See Update field through link_to in Rails for how to do this using link_to instead of a form.

Community
  • 1
  • 1
graphmeter
  • 1,125
  • 1
  • 9
  • 24

1 Answers1

1

Try

<%= f.hidden_field :parent_id, value: nil %>

instead of

<%= f.hidden_field parent_id: nil %>

And make sure parent_id is in attr_accessible list of the model.

alex
  • 3,682
  • 3
  • 21
  • 22
  • Thanks, but I get an error `undefined method `merge' for nil:NilClass`, using :parent_id, nil...? – graphmeter Dec 03 '12 at 20:31
  • 1
    If you are using the form helper version then you should not pass a second parameter. Either of the following should work: `f.hidden_field :parent_id` or `hidden_field_tag :parent_id, nil`. – Andrew Hubbs Dec 03 '12 at 21:38
  • @AndrewHubbs: Thanks. With `f.hidden_field :parent_id` I cannot update the value of parent_id to nil? I don't get an error with `hidden_field_tag :parent_id, nil`, but it doesn't seem to update the value of the field (also tried other fields than parent_id, e.g. :name which doesn't work either)? – graphmeter Dec 04 '12 at 08:36
  • graphmeter, try `<%= f.hidden_field :parent_id, value: nil %>` – alex Dec 04 '12 at 12:31
  • @alex: Thanks a lot! Works great with value: nil. – graphmeter Dec 04 '12 at 14:32
  • If a `hidden_field_tag :parent_id, nil` is used the `parent_id` has to be picked up in the controller: `@product.parent_id = params[:parent_id]`. – graphmeter Dec 04 '12 at 15:25