我在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
...
然后在我看来(.html.haml
文件),我试图打印字段:
...
%li
- if this_user.has_car
= "This person has a car"
- else
= "This person does NOT have a car"
...
出于某种原因,this_user.has_car
始终评估为false
。
谁能告诉我这里做错了什么? (我对Ruby / Rails很新)
由于
答案 0 :(得分:8)
您可以在用户模型中定义名为has_car?
的方法
# user.rb
def has_car?
age > 18
end
然后在您的视图中使用this_user.has_car?
。
答案 1 :(得分:1)
# app/models/user.rb
class User < ActiveRecord::Base
attr_accessible :name, :age, :has_car
def initialize
# Everyone does not have a car
self.has_car = false
end
def has_car?
self.has_car || self.age >= 18
end
def purchase_car
self.has_car = true
end
def sell_car
self.has_car = false
end
end
当您致电user = User.new
或user = User.create
时,会使用初始化方法。此方法只是将该实例的has_car
设置为false。
然后,您可以询问user.has_car?
,如果用户有车(他们已经购买了一辆车)或者他们年满18岁,那么它将返回true。
因为16岁(在某些州)可以买车,你可以致电user.purchase_car
来指明他们现在拥有一辆车。 has_car?
方法在检查has_car
之前检查age
数据库列。
sell_car
方法做了类似的事情,但它将user.has_car
设置为false。
希望这有助于您在Learn Ruby on Rails
任务中获得好运!
答案 2 :(得分:0)
这个方法不应该这样读吗?
def init(age)
if age > 18
has_car = true
else
has_car = false
end
return has_car
end