[英]How to add user_id in form params in Rails controller
I have this model, called products
, that has an id
, user_id
and product_name
. 我有一个称为
products
模型,该模型具有一个id
, user_id
和product_name
。 I have a simple form_for
to pass to my product_controller
the product_name
param. 我有一个简单
form_for
传递给我的product_controller
的product_name
PARAM。 In this same controller, I have access to the current_user
, which I have to pass in order to create a new Product
. 在同一个控制器中,我可以访问
current_user
,我必须通过current_user
才能创建新的Product
。 The problem is that the user_id
always has to be the current user logged in, so I can't allow the user to send me this param in my form_for
, thus I can't permit
it as well. 问题在于,
user_id
始终必须是当前登录的用户,因此我不允许用户在我的form_for
向我发送此参数,因此我也permit
。 What I'm doing right now is to create a new hash with the user_id
param, and merge the params that comes from the form
. 我现在正在做的是使用
user_id
参数创建一个新的哈希,并合并来自form
的参数。
products_controller.rb:
def create
product_user_id_param = { "user_id": current_user.id.to_s }
@product = Product.new(product_user_id_param.merge(params[:product_name]))
...
end
Is there a more convenient or Rails way to do this? 有没有更方便的方法或Rails的方法来做到这一点?
Solution #1 解决方案1
Product has user_id
which means product belongs_to :user
and user has_many :products
产品具有
user_id
,这表示product belongs_to :user
和user has_many :products
Hence it can be written as 因此可以写成
current_user.products.new(product_name: params[:product_name])
Solution#2 解决方案#2
Set current_user explicitly 显式设置current_user
@product = Product.new(product_name: params[:product_name])
@product.user_id = current_user.id
#@product.user = current_user
@product.save
You can create you product with you current_user reference, this is the more convenient way in my opinion: 您可以使用current_user参考创建产品,我认为这是更方便的方法:
current_user.produtcs.create(name: params[:product_name])
But, to above code works, you have to construct you relations correctly, like the following: 但是,要使以上代码正常工作,您必须正确构建关系,如下所示:
class User < ActiveRecord::Base
has_many :products
end
class Product < ActiveRecord::Base
belogs_to :user
end
Now, you can do it! 现在,您可以做到!
You can read more about it, in https://guides.rubyonrails.org/v3.2/association_basics.html , the docs recommeds this way! 您可以在https://guides.rubyonrails.org/v3.2/association_basics.html中了解更多有关此文档的信息!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.