[英]Rails: Nested Forms - passing the user_id from parent to child
I'm trying to pass the user_id from the parent model ( Order ) to the child model ( Sale ). 我试图将user_id从父模型( Order )传递到子模型( Sale )。 As this does not work the "normal" way, like
@sale.user_id = current_user.id
(this actually works for the parent model Order
with @order.user_id = current_user.id
). 因为这不
@sale.user_id = current_user.id
“常规”方式,例如@sale.user_id = current_user.id
(这实际上适用于父模型Order
,其@order.user_id = current_user.id
)。 I tried this in my model as a workaround: 我在模型中尝试了以下方法:
class Sale < ActiveRecord::Base
belongs_to :order
before_create :user
def user
self.user_id = Order.where(:id => self.order_id).pluck(:user_id)
end
end
Within user
I'm comparing the Order .id (parent) with the Sale .order_id (child) as the order_id
gets saved within a Sale record. 在
user
我将Order .id(父级)与Sale .order_id(子级)进行比较,因为order_id
保存在Sale记录中。 When I look up the last Sale record, the user_id
is always nil
. 当我查找最后的Sale记录时,
user_id
始终为nil
。
class SalesController < ApplicationController
load_and_authorize_resource
before_action :authenticate_user!
def create
@order = Order.find(params[:order_id])
@sale = @order.sales.create(params[:sale].permit(:product, :product_group, :discount, :order_id, :user_id, :multiplier))
redirect_to order_path(@order)
end
Do you have an Idea? 你有想法吗?
Try this in your model. 在您的模型中尝试一下。
def user
self.user_id = self.order.user_id
end
params[:sale].permit(:product, :product_group, :discount, :order_id , :user_id , :multiplier)
params [:sale] .permit(:product,:product_group,:discount, :order_id , :user_id ,:multiplier)
Firstly, you should not permit user_id
& order_id
in your controller. 首先,您不应在控制器中允许
user_id
和order_id
。
Secondly, you can populate your Sale's user_id
as follow: 其次,您可以按如下方式填充销售的
user_id
:
def user
user_id = order.user_id
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.