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.