[英]Rails Optional Sign Up - Changing Params Before Saving
I'm developing an application with optional sign up. 我正在开发带有可选注册的应用程序。 I want to allow users, with and without accounts, to be able to add links. 我想允许具有和不具有帐户的用户添加链接。 How could I assign a user's session[user_id]
to the user_id
column of Link
if they're signed in when creating a link? 如果创建链接时用户已session[user_id]
如何将用户的session[user_id]
分配给Link
的user_id
列?
Current code: user_id
remains nil in either case 当前代码:无论哪种情况, user_id
保持为零
def create
@link = Link.new(params[:link])
if @link.save
flash[:notice] = "The link was successfully added"
redirect_to :action => :hot
else
redirect_to :action => :new
end
end
I'm imagining something like this.. 我在想像这样的事情。
def create
if session[:user_id]
#@link equals new link params with user_id = session[:user_id]
else
@link = Link.new(params[:link])
end
if @link.save
flash[:notice] = "The link was successfully added"
redirect_to :action => :hot
else
redirect_to :action => :new
end
end
def create
@link = Link.new params[:link]
@link.user_id = session[:user_id] if session[:user_id]
if @link.save
redirect_to { action: 'hot' }, notice: 'The link was successfully added'
else
render :new
end
end
The link will be saved with params[:link] even if the user isn't logged-in. 即使用户未登录,该链接也将使用params [:link]保存。
Be cautious to use render, not redirect_to, when a validation fails (see if you want http://guides.rubyonrails.org/action_controller_overview.html ) 验证失败时,请谨慎使用渲染,而不是redirect_to(请参见是否要http://guides.rubyonrails.org/action_controller_overview.html )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.