2016-06-17 24 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