40

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)
2
  • 1
    I'm curious - what's wrong with using hidden fields? Commented Mar 13, 2011 at 0:43
  • 1
    @sscirrus: Hidden fields can be seen in the HTML source on the client. If you want to add sensitive information to the model (i.e. UUID), then it would be better to add the field to the model on the server-side. Commented Sep 24, 2012 at 15:25

3 Answers 3

79

I use this day in and day out:

@page= Page.new(params[:page].merge(:user_id => 1, :foo => "bar"))
Sign up to request clarification or add additional context in comments.

2 Comments

I just want to add that this works with an unlimited number of attributes.
will this work if I do (:user_id => 1).merge(params) ?
19

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.

1 Comment

@Rails101: current_user.pages.build(params[:page].merge(:other_id => other_id)
4

Instead of trying to merge the current_user id, you can build the proper model associations and then scope the new() method

Models

class Page < ActiveRecord::Base
 belongs_to :user
end

class User < ActiveRecord::Base
 has_many :pages
end

Controller

if current_user
 @page = current_user.pages.new(params[:page])
else
 @page = Page.new(params[:page])
end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.