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
我怎样才能检索和存储在Item
的shop_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 %>
如果您能给我任何建议,我们将不胜感激。
感谢您快速的解答,@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
它编辑后如下,@Emu。感谢您的时间。 '<%= link_to“添加商品”,new_shop_item_path(商店)'。 – SamuraiBlue
@SamuraiBlue,非常欢迎。 :) – Emu