SamuraiBlue
SamuraiBlue

Reputation: 861

Rails: How to store the parent data in the child model (association)

My models are as followings;

models

shop.rb

class Shop < ActiveRecord::Base
    belongs_to :order
    has_many :items
    has_many :categories
end

item.rb

class Item < ActiveRecord::Base
    belongs_to :shop
    has_many :categories
end

How can I retrieve and store the shop_id in the Item when I save item data?

Although I think something like @item.shop works, I don't know how to apply it.

schema

ActiveRecord::Schema.define(version: 20160615060137) do

...

  create_table "shops", force: :cascade do |t|
    t.string   "name"
    t.integer  "order_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "items", force: :cascade do |t|
    t.string   "name"
    t.integer  "shop_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

...

end

items_controller.rb

class ItemsController < ApplicationController

  def new
    @item = Item.new
  end

  def create
    @item = Item.new(item_params)
    if @item.save
      flash[:success] = "item created!"
      redirect_to root_url
    else
      render 'new'
    end
  end

  private

    def item_params
      params.require(:item).permit(:name, :shop_id)
    end

end

views/items/new.html.erb

<%= form_for(@item) do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name %>
    <br>
    <%= f.submit "Post" %>
<% end %>

It would be appreciated if you could give me any suggestion.

Upvotes: 0

Views: 184

Answers (1)

Emu
Emu

Reputation: 5895

You can do it in 3 ways,

Dirty: add a hidden_field named shop_id in the item/_form and assign the hidden_field to your value.

Best: Create nested object. In the route file do:

resources :shops do
 resources :items
end

It'll generate an new item path like root_url/shops/1/items/new. thus you can get the shop_id

OR

You can create the new item object with a shop like:

def new
  @shop = Shop.find(params[:shop_id])
  @item = @shop.items.new
end

Upvotes: 1

Related Questions