2016-06-17 47 views
0

我的模型如下:Rails:如何將父數據存儲在子模型(關聯)中

模式

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 

我怎樣才能檢索和存儲在Itemshop_id當我保存item數據?

儘管我認爲像@item.shop這樣的作品,我不知道如何應用它。

模式

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 

的意見/項目/ new.html.erb

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

如果您能給我任何建議,我們將不勝感激。

回答

1

你可以做到這一點有3種方式,

髒:添加一個名爲hidden_fielditem/_formshop_id並分配hidden_​​field到你的價值。

最佳:創建嵌套對象。在路由文件做:

resources :shops do 
resources :items 
end 

它會產生這樣的root_url/shops/1/items/new項目new路徑。因此,你可以得到shop_id

OR

可以createshopnew項目目標:

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

感謝您快速的解答,@Emu。雖然它在我在'routes.rb'中添加第二個答案後直接輸入url時起作用,但當我添加'<%= link_to「時,顯示以下錯誤:在shop.html中添加事件」new_shop_item_path%>「 .erb'。錯誤是'ActionController :: UrlGenerationError in ShopsController#show' and'No route matches {:action =>「new」,:controller =>「items」,:id =>「23」}缺少必需的鍵:[:shop_id ]'。 – SamuraiBlue

+1

它編輯後如下,@Emu。感謝您的時間。 '<%= link_to「添加商品」,new_shop_item_path(商店)'。 – SamuraiBlue

+0

@SamuraiBlue,非常歡迎。 :) – Emu

相關問題