Rails 4: Insert Attribute in Params

Rails 3 introduced the ability to insert an attribute in the following parameters:

params[:post][:user_id] = current_user.id 

I am trying to do something similar in Rails 4 but with no luck:

 post_params[:user_id] = current_user.id . . . . private def post_params params.require(:post).permit(:user_id) end 

Rails ignores this insert. It does not cause any errors; it simply fails.

+64
ruby-on-rails strong-parameters
May 13 '13 at 20:27
source share
4 answers

Found the answer here . Instead of inserting an attribute from a controller action, you can insert it into the parameter definition using merge. To expand on my previous example:

 private def post_params params.require(:post).permit(:some_attribute).merge(user_id: current_user.id) end 
+133
May 13 '13 at 10:12
source share

In addition to @timothycommoner's answer, you can also perform a merge for each action:

  def create @post = Post.new(post_params.merge(user_id: current_user.id)) # save the object etc end private def post_params params.require(:post).permit(:some_attribute) end 
+35
Jun 13 '14 at 16:57
source share

Alternatively for this case, you can get the pass attribute through scope :

current_user.posts.create(post_params)

+3
Jul 12 '16 at 10:29
source share

If someone is trying to figure out how to add / edit a nested attribute in a Rails 5 attribute hash, I find this to be the easiest (alternative) approach. Do not worry about merging or deep_merge ... this is a pain due to strong parameters. In this example, I needed to copy group_id and vendor_id to the corresponding invoice (nested parameters) before saving.

 def create my_params = order_params @order = Order.new @order.attributes = my_params @order.invoice.group_id = my_params[:group_id] @order.invoice.vendor_id = my_params[:vendor_id] @order.save end private # Permit like normal def order_params params.require(:order).permit([:vendor_id, :group_id, :amount, :shipping,:invoice_attributes => [:invoice_number, :invoice_date, :due_date, :vendor_id, :group_id]]) end 
0
May 27 '19 at 19:44
source share



All Articles