简体   繁体   中英

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)

我每天都在使用这一天:

@page= Page.new(params[:page].merge(:user_id => 1, :foo => "bar"))

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM