坚持嵌套表格..
订单型号:
class Order < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
用户模式:
class User < ActiveRecord::Base
has_many :orders, dependent: :destroy
accepts_nested_attributes_for :orders
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
表单视图:
=form_for @order do |order|
=order.fields_for :user, @order.user do |user|
.row
.col-md-3
.form-group
=user.label :first_name, "Name"
=user.text_field :first_name, :class => "form-control"
.col-md-3
.form-group
=user.label :last_name, "Last name"
=user.text_field :last_name, :class => "form-control"
.col-md-3
=user.label :email, "Email"
=user.text_field :email, :class => "form-control"
.col-md-3
=user.label :telephone, "Phone"
=user.text_field :telephone, :class => "form-control"
.row
.col-md-4.margin-top-15
=order.submit 'Send', :class => 'btn btn-success'
OrdersController:
class OrdersController < ApplicationController
def new
@order = Order.new
if user_signed_in?
user = current_user
else
user = User.new
end
end
def create
@order = Order.new order_attributes
@order.save
end
private
def order_attributes
params.require(:order).permit(:user_id, user_attributes: [:id, :user_id, :user, :first_name, :last_name, :email, :telephone, :password, :password_confirmation])
end
end
所以这就是我想要做的事情:
用户模型已经设计好了。我想创建订单并为其分配user_id。在提交时,它告诉我&#34;未经许可的参数:user&#34;。订单模型会创建其列,但不会转到用户模型。
我做错了什么?
答案 0 :(得分:0)
更改:
params.require(:order).permit(:user_id, user_attributes: [:id,...
为:
params.require(:order).permit(:user_id, user: [:id,...
答案 1 :(得分:0)
从:user
移除:user_attributes
。
我不认为:user_id
是必要的。