Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean value in ruby on rails

I've declared some simple boolean field in my model/user.rb

class User < ActiveRecord::Base
attr_accessible :name, :has_car

def  init(age)
 if age > 18
   has_car = true
 else
   has_car = false
 end
   has_car
end
...

Then in my view (.html.haml file), I tried to just print the field:

...
%li
 - if this_user.has_car
   = "This person has a car"
 - else
   = "This person does NOT have a car"
...

For some reason, this_user.has_car always evaluates to false. Could anyone tell me what I did wrong here? (I'm very new to Ruby/Rails)

Thanks

like image 497
One Two Three Avatar asked Jun 06 '26 21:06

One Two Three


1 Answers

you can define a method called has_car? in the user model

# user.rb
def has_car?
  age > 18
end

then just use this_user.has_car? in your view.

like image 75
jvnill Avatar answered Jun 09 '26 12:06

jvnill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!