catmal
catmal

Reputation: 1758

Rails pass param on create action through form

I have models Item and ItemCategory. Item belongs_to ItemCategory.

On Item form, I want to be able to create a new ItemCategory and assign it to current item.

So I added on Item form:

<%= link_to '+', new_quick_category_path(item_id: @item.id), remote: true %>

Then on items_controller:

  def new_quick_category
    @item_category = ItemCategory.new
    @item = Item.find(params[:item_id])
  end

I get then the form:

<%= simple_form_for (@item_category), html: { id: :item_category}, remote: true do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<h5> Name </h5>
<%= f.input :name, label: false %>

  <%= f.button :submit, "Create", class: "btn btn-sm btn-success" %>
<% end %>

Now to update the current item with newly created item_category I assume I need to do on item_categories_controller:

    def create
    @item = Item.find(params[:item_id])
    @item.update_attributes(item_category_id: @item_category.id)
    ....
    end

So I need to pass the param item_id to create action on item_categories_controller.

A solution that comes to my mind would be passing it on create button on form like:

  <%= f.button :submit, "Create"(item_id: @item.id), class: "btn btn-sm btn-success" %>

but it doesn't work.

How can I do it? Or should I make a nested form instead?

Upvotes: 0

Views: 78

Answers (1)

Manoj Menon
Manoj Menon

Reputation: 1038

Please try to set item as hidden field in form, so it can be send to controller when you submit the form, hidden field should get the value from params like this

<%= hidden_field_tag :item_id, params[:item_id] %>

Upvotes: 2

Related Questions