Reputation: 469
Back again with a Boolean method definition question for beginners.
Here is the method I'd like to write:
def has_booth?
end
I'm not quite sure what to pass as the argument. I want this to return true for users that have created a booth and false for those that haven't. Booths are associated with a user id and each user can has_one booth. Booths also have a name parameter.
I tried things like
booth.id.nil?
and
booth_id.nil?
and
booth.name.nil?
and
booth.name != nil
and
if current_user
if session[:booth_id]
Can you please guide me as to what I'm doing incorrectly or point me towards some literature? I have seen a bunch of tutorials for creating simple methods that have simple arguments and return or puts something on a screen, but nothing that seems to help me move the needle. I'd like to do this as correctly as possible.
If it is helpful, here is my booths controller:
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
I appreciate any help or guidance towards a solution. Thanks!
Upvotes: 0
Views: 7204
Reputation: 3638
You could use the exists?
method:
Booth.exists?(user_id: id) # Return true if exists a Booth with user_id == id
Your method will look like this:
def has_booth?(user_id)
Booth.exists?(user_id: user_id)
end
Although, you should put that method in the User
model:
class User < ActiveRecord::Base
has_one :booth
def booth? # It's convention booth? instead of has_booth?
!!self.booth
end
end
Then in your views you could just call the method on your users:
<% if current_user.booth? %> ...
Upvotes: 1