Ruby on rails 4 定义布尔方法Ruby初学者

Ruby on rails 4 定义布尔方法Ruby初学者,ruby-on-rails-4,boolean,Ruby On Rails 4,Boolean,再次为初学者解答布尔方法定义问题 下面是我想写的方法: def has_booth? end 我不太确定该把什么作为论点。我希望对于已经创建展位的用户返回true,对于没有创建展位的用户返回false。展位与用户id关联,每个用户可以拥有一个展位。展位也有一个名称参数 我试过这样的方法 booth.id.nil? 及 及 及 及 你能不能告诉我我做错了什么,或者告诉我一些文献?我已经看过一系列关于创建简单方法的教程,这些方法有简单的参数并返回或在屏幕上显示一些内容,但似乎没有任何东西能帮助

再次为初学者解答布尔方法定义问题

下面是我想写的方法:

def has_booth?
end 
我不太确定该把什么作为论点。我希望对于已经创建展位的用户返回true,对于没有创建展位的用户返回false。展位与用户id关联,每个用户可以拥有一个展位。展位也有一个名称参数

我试过这样的方法

booth.id.nil?

你能不能告诉我我做错了什么,或者告诉我一些文献?我已经看过一系列关于创建简单方法的教程,这些方法有简单的参数并返回或在屏幕上显示一些内容,但似乎没有任何东西能帮助我移动指针。我想尽可能正确地做这件事

如果有帮助,这里是我的展位控制器:

class BoothsController < ApplicationController
  before_action :logged_in_user

  def index
    @booths = Booth.all
  end

  def new
    @booth = Booth.new
  end

  def create
    @booth = current_user.build_booth(booth_params)
    if @booth.save
      flash[:success] = "Congrats on opening your booth!"
      redirect_to root_url
    else
      render 'new'
    end
  end

  def show
    @user = User.find(params[:id])
    @booth = Booth.find(params[:id])
  end

  private

    def booth_params
      params.require(:booth).permit(:name)
    end
end
class boothcontroller

我感谢任何对解决方案的帮助或指导。谢谢

您可以使用
存在?
方法:

Booth.exists?(user_id: id) # Return true if exists a Booth with user_id == id
您的方法如下所示:

def has_booth?(user_id)
  Booth.exists?(user_id: user_id)
end 

但是,您应该将该方法放在
用户
模型中:

class User < ActiveRecord::Base
  has_one :booth

  def booth? # It's convention booth? instead of has_booth?
    !!self.booth
  end
end
class用户
然后在视图中,您可以对用户调用该方法:

<% if current_user.booth? %> ...
。。。

您想将方法放在哪里?您好,谢谢您的建议。当我添加此代码并在我的erb中包含“”时,我得到一个错误,显示“参数数量错误(0代表1)”提取的源代码(在第3行附近):1 2 3 4 5 6模块引导Helper def有引导?(用户id)引导。存在?(用户id:用户id)结束“知道为什么会发生这种情况吗?谢谢你的帮助。你需要提供一个用户id。
has_booth?(current_user.id)
可能有用谢谢Mario。我认为这是可行的,但我对erb输出仍然有问题。我可能会将它作为另一个问题提交,因为我找不到其他类似的问题,它可能会对其他人有所帮助。挫折感永远不会结束。哈哈,这正是我的感受。
Booth.exists?(user_id: id) # Return true if exists a Booth with user_id == id
def has_booth?(user_id)
  Booth.exists?(user_id: user_id)
end 
class User < ActiveRecord::Base
  has_one :booth

  def booth? # It's convention booth? instead of has_booth?
    !!self.booth
  end
end
<% if current_user.booth? %> ...