简体   繁体   English

如何在Rails控制器的表单参数中添加user_id

[英]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模型,该模型具有一个iduser_idproduct_name I have a simple form_for to pass to my product_controller the product_name param. 我有一个简单form_for传递给我的product_controllerproduct_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 :useruser 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM