Ruby-on-rails 将变量添加到 rails 中的 params
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4350499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding variable to params in rails
提问by Rails101
How can i add user_id into params[:page] i don't want to use hidden fields.
如何将 user_id 添加到 params[:page] 我不想使用隐藏字段。
@page= Page.new(params[:page])
Is there a way to use like
有没有办法使用像
@page= Page.new(:name=>params[:page][:name], :user_id => current_user.id)
回答by efalcao
I use this day in and day out:
我日复一日地使用这个:
@page= Page.new(params[:page].merge(:user_id => 1, :foo => "bar"))
回答by Ryan Bigg
Instead of doing it that way, build the association (assumes you have has_many :pagesin the Usermodel):
不要那样做,而是建立关联(假设您has_many :pages在User模型中有):
@page = current_user.pages.build(params[:page])
This will automatically set user_idfor the Pageobject.
这将自动user_id为Page对象设置。
回答by Carles Jove i Buxeda
Instead of trying to merge the current_userid, you can build the proper model associations and then scope the new()method
current_user您可以构建适当的模型关联,然后确定new()方法的范围,而不是尝试合并id
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

