LovingRails LovingRails - 9 months ago 34
Ruby Question

Is it okay to read date from database in the view template in Ruby on Rails?

I am revisiting the basics of MVC and Ruby on Rails. I am looking at my code and found that I have used this select tag in my Edit User Profile view.

<div class="row">
<div class="panel panel-primary">

<div class="panel-heading">
<%= f.label :country_id, "From*" %>

<div class="panel-body">
<%= f.select :country_id, Country.order(:name).collect {|p| [ p.name, p.id ] }, {}, { :class => 'form-control' } %>

I am accessing the Country table in the view. I am pretty sure this should not be done but somehow it works. Why does it work? What is the correct way to do it?



There's no reason why what you have won't work. Remember, a view template is an "embedded ruby" file. It has Ruby embedded in an HTML template. When the view is "rendered" by the controller, all of the code inside it gets executed and whatever output is generated by its Ruby code becomes part of the HTMl document. In this case, the output generated by the Ruby code is a bunch of HTML tags and Country names and IDs.

To avoid having this logic in the view, you would put it in the controller and save it to an instance variable (i.e. something like @select_vals) and then reference that variable in the view template.