简体   繁体   English

Rails,Devise:如果用户登录时使用用户ID创建,否则不添加

[英]Rails, Devise: If user signed in create with user id, else without

I have a streams controller and I am using Devise. 我有一个流控制器,正在使用Devise。 Users can create streams either with (than the stream will have the id of the user in the db) or without account(than its a guest stream so to say). 用户可以创建具有(而不是在db中具有该用户的ID的流)用户ID的流,也可以不具有(创建其宾客流的)流帐户的流。 Currently I have the following create method: 目前,我有以下创建方法:

def create
  @stream = current_user.streams.build(params[:name])
  if @stream.valid?
    @stream.save
    redirect_to c_path(@stream.name)
    flash[:notice] = "blabla"
  else
    redirect_to root_path
  end
end

But that doesnt work for guests, since I use the current_user. 但这不适用于客人,因为我使用current_user。 Now my plan was to create a if else (if signed in use the current_user, else not). 现在,我的计划是创建一个if else(如果使用current_user登录,则不是)。

How would I do that? 我该怎么做?

Thanks! 谢谢!

It's quite simple, you can use user_signed_in? 很简单,您可以使用user_signed_in? helper: 帮手:

if user_signed_in?
  @stream = current_user.streams.build(params[:name])
else
  @stream = Stream.new(params[:name])
end

BTW make sure you pass valid params while building object. BTW确保在构建对象时传递有效的参数。

Devise has a user_signed_in? 设计有一个user_signed_in吗? method. 方法。 So you could do this: 因此,您可以这样做:

if user_signed_in?
  @stream = current_user.streams.build(params[:name])
else
  @stream = Stream.new(params[:name])
end  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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