2016-04-15 39 views
2

我在我的rails视图中有信息,我只想显示用户是否输入了数据库中的所有个人详细信息,例如姓名,街道和城市。我现在可以做到这一点:rails检查表单是否完全填写

if user.name && user.firstname && user.street && user.street 
# show stuff 
end 

但我不认为这是非常优雅的“铁轨方式”。有没有更容易和更聪明的方法来做到这一点?

回答

3

您可以在模型类的html表单标签和验证中使用required。也跟随链接: http://guides.rubyonrails.org/active_record_validations.html http://www.w3schools.com/tags/att_input_required.asp

在模型中

class User < ActiveRecord::Base 
    def has_required_fields? 
    self.name && self.first_name && self.address && .... 
    end 
end 

而在你的控制器

if user.has_required_fields? 
    # do whatever you want 
end 
+0

没有。我想独立于表单过滤信息。 – DonMB

+0

我有更新答案。现在检查。 –

0

的 “轨道路” 将是瘦控制器,脂肪模型。因此,对于您的情况,您希望在User型号中创建一个方法,然后在控制器中使用它。

用户模式

def incomplete? 
    name.blank? or firstname.blank? or street.blank? 
end 

用户控制器

unless user.incomplete? 
    # Show stuff 
end 
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。

看起来很优雅:)这是不是我想要做的