我的项目是关于一个在线购物网站,使用Ruby on Rails购买手机。
我的网站有一个添加手机的页面 - 三星,诺基亚......而在三星,它有很多设备。 我如何获得三星的ID来创建一个类型为'三星'的新手机。三星在产品表中,手机在电话表中。
class Phone < ActiveRecord::Base
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :phones
end
这是产品的动作节目:
<h1>Your item</h1>
<h3><%= @product.name %></h4>
<% if logged_in?%>
<% if current_user.admin? %>
<%= link_to 'Edit',edit_product_path%>
<%end%>
<%end%>
<%= link_to 'Home',welcome_home_path%>
<%= link_to 'New item',new_phone_path %>
<%= link_to 'Create new phone',new_phone_path%> #It links to action new of Phones
但我无法获得Product的ID:`object_product.phones.create
class PhoneController < ApplicationController
def new
end
def show
@phone = Phone.find(params[:phone_id])
end
def create
@product = Product.find(params[:product_id])
@phone = @product.phones.create(phone)
redirect_to product_phone_path
end
private
def phone
params.require(:phone).permit(:name,:num)
end
end
答案 0 :(得分:0)
您可以在路线上拥有嵌套资源,例如:
resources :product do
resources :phone
end
并在您的产品视图中添加此网址助手new_product_phone_path
,而不是new_phone_path
。
所以现在你的新路线如下:
/product/:product_id/phone/new
新控制器:
def new
@phone=Phone.new
end
现在,如果您在表单中有以下内容:
<%= form_for @phone do |f| %>
<%= f.label :name %>:
<%= f.text_field :name %><br />
<%= f.submit %>
<% end %>
您的控制器操作将如下所示:
def create
@phone=Phone.create(name: params[:name])
@product=Product.find(params[:product_id])
@product.phones << @phone
end