I have information in my rails view that I only want to show up if the user has entered all personal details in the database, such as name, firstname, street and city. I could now do this:
if user.name && user.firstname && user.street && user.street
# show stuff
end
but I don't think that is very elegant and "the rails way". Is there an easier and smarter way to do this?
答案 0 :(得分:3)
You can use required
in your html form tags and validations in Model Class. Also follow links:
http://guides.rubyonrails.org/active_record_validations.html
http://www.w3schools.com/tags/att_input_required.asp
In your model
class User < ActiveRecord::Base
def has_required_fields?
self.name && self.first_name && self.address && ....
end
end
And in your controller
if user.has_required_fields?
# do whatever you want
end
答案 1 :(得分:0)
“轨道方式”将是瘦控制器,胖模型。因此,在您的情况下,您需要在User
模型中创建一个方法,然后在控制器中使用它。
用户模型:
def incomplete?
name.blank? or firstname.blank? or street.blank?
end
用户控制器:
unless user.incomplete?
# Show stuff
end
答案 2 :(得分:0)
:
ALL_REQUIRED_FIELDS = %w(name surname address email)
def filled_required_fields?
ALL_REQUIRED_FIELDS.all? { |field| self.attribute_present? field }
end
在您的控制器中:
@user.filled_required_fields?
如果填写了所有字段,将返回true,否则返回false。
看起来非常优雅:)