kaneru kaneru - 6 months ago 8
Ruby Question

When create an item within a category, the item can't get the category_id

I am building ecommerce using Rails and I got stuck with this problem:

When I try to create a new item within some category from a browser, the created item doesn't get an id of the category.

http://localhost:3000/categories/1/items/new


In console I can verify that params get the category_id correctly:

Parameters: {"category_id"=>"1"}


After creating the item's category_id equals to nil.

Here's my Item model file:

class Item < ActiveRecord::Base
belongs_to :category
end


Category model:

class Category < ActiveRecord::Base
has_many :items
end


This is my items_controller.rb file where I pass category_id to the Item:

class ItemsController < ApplicationController
# other actions are ommited
def new
@item = Item.new
@item.category_id = params[:category_id]
end
end


Also you can look at the whole app in:
https://github.com/kaneru/estore

Thanks in advance.

dkp dkp
Answer

Your views/items/_form.html.erb should look as follows:

<div class="row">
  <div class="col-lg-4 col-md-offset-4">
  <%= simple_form_for @item do |f| %>
    <%= f.hidden_field :category_id,value: params[:category_id] %>
    <%= f.input :title %>
    <%= f.input :price %>
    <%= f.input :color %>
    <%= f.input :weight %>
    <%= f.input :description, as: :text %>
    <%= f.input :picture, as: :file %>
    <%= f.button :submit, class: "btn btn-primary" %>
  <% end %>

  <br/>
  <%= render "menu" %>
  </div>
</div>