Reputation: 2728
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?
Upvotes: 3
Views: 858
Reputation: 753
in model:
ALL_REQUIRED_FIELDS = %w(name surname address email)
def filled_required_fields?
ALL_REQUIRED_FIELDS.all? { |field| self.attribute_present? field }
end
in your controller:
@user.filled_required_fields?
will return true if all fields filled and false if not.
looks very gracefully :)
Upvotes: 0
Reputation: 339
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
Upvotes: 3
Reputation: 182
The "rails way" would be thin controller, fat model. So, in your case, you'd want to create a method inside your User
model and use it in your controller afterwards.
User model:
def incomplete?
name.blank? or firstname.blank? or street.blank?
end
User controller:
unless user.incomplete?
# Show stuff
end
Upvotes: 0