Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I have a simple form_for to pass to my product_controller the 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. 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. 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.

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?

like image 335
Anna Avatar asked Nov 19 '25 07:11

Anna


1 Answers

Solution #1

Product has user_id which means product belongs_to :user and user has_many :products

Hence it can be written as

current_user.products.new(product_name: params[:product_name])

Solution#2

Set current_user explicitly

@product = Product.new(product_name: params[:product_name])
@product.user_id = current_user.id
#@product.user = current_user
@product.save
like image 96
Anand Avatar answered Nov 20 '25 20:11

Anand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!