kaneru kaneru - 1 year ago 57
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.


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

Category model:

class Category < ActiveRecord::Base
has_many :items

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]

Also you can look at the whole app in:

Thanks in advance.

dkp dkp
Answer Source

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 %>

  <%= render "menu" %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download