Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding variable to params in rails

How can i add user_id into params[:page] i don't want to use hidden fields.

@page= Page.new(params[:page]) 

Is there a way to use like

@page= Page.new(:name=>params[:page][:name], :user_id => current_user.id) 
like image 790
Rails101 Avatar asked Dec 03 '10 22:12

Rails101


People also ask

How do params work in Rails?

Specifically, params refers to the parameters being passed to the controller via a GET or POST request. then the controller would pass in {:name => “avi”} to the show method, which would set the @person instance variable to the person in the database with the name “avi”.

What are strong parameters in Rails?

Strong Parameters, aka Strong Params, are used in many Rails applications to increase the security of data sent through forms. Strong Params allow developers to specify in the controller which parameters are accepted and used.

What does params fetch do?

Returns a parameter for the given key.


2 Answers

I use this day in and day out:

@page= Page.new(params[:page].merge(:user_id => 1, :foo => "bar")) 
like image 159
efalcao Avatar answered Sep 28 '22 01:09

efalcao


Instead of doing it that way, build the association (assumes you have has_many :pages in the User model):

@page = current_user.pages.build(params[:page]) 

This will automatically set user_id for the Page object.

like image 38
Ryan Bigg Avatar answered Sep 28 '22 00:09

Ryan Bigg