簡體   English   中英

在rails中為params添加變量

[英]Adding variable to params in rails

如何將user_id添加到params [:page]我不想使用隱藏字段。

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

有沒有辦法使用像

@page= Page.new(:name=>params[:page][:name], :user_id => current_user.id)

我每天都在使用這一天:

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

而不是這樣做,建立關聯(假設你有User模型中的has_many :pages ):

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

這將自動為Page對象設置user_id

您可以構建正確的模型關聯,然后調整new()方法的范圍,而不是嘗試合並current_user id

楷模

class Page < ActiveRecord::Base
 belongs_to :user
end

class User < ActiveRecord::Base
 has_many :pages
end

調節器

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM