Reputation: 487
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?
Upvotes: 3
Views: 2016
Reputation: 1287
You can create you product with you current_user reference, this is the more convenient way in my opinion:
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!
Upvotes: 3
Reputation: 6531
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
Upvotes: 4