Ruby on Rails. Understanding loops -
i'm getting somewhere ror. want clarify things regarding loops.
i've created 'inputs' controller contains methods let user create, read, update , delete database entries.
i have 'inputs' view renders html frontend. in view following loop:
<table> <% @inputs.each |input| %> <tr> <td><%= input.title %></td> <td><%= input.content %></td> <td><%= link_to 'show', input %></td> <td><%= link_to 'edit', edit_input_path(input) %></td> <td><%= link_to 'destroy', input, method: :delete, data: { confirm: 'are sure?' } %> </td> </tr> <% end %> </table>
i understand how loops work conceptually, i'm bit lost on this.
i think @inputs
'points code' (better way of expressing that, please?) towards inputs controller the methods used loop live.
inside inputs controller there indeed methods such 'edit', 'create', 'show' , 'destroy'.
but there not 'title' or 'content' methods in controller! come from?
and, honest, not understand
<% @inputs.each |input| %>
very well.
this me trying understand:
@inputs = go inputs controller
.each = call each method on inputs controller. (where each method defined? mean, calling each on controller?)
do | input | = whatever heck calling .each on controller does, generates object called 'input'.
now, object 'input' indeed contain methods such title , content, these methods coming from?? literally inside controller!
anyway, lot.
when use @inputs
inside view template you've shown in code above, view template using instance variable @inputs
has been defined inside controller action rendered view template.
in other words, use example, let's inputscontroller
has method called index
. in view folder, have corresponding view template named index.html.erb
.
# inside app/controllers/inputs_controller.rb def index @inputs = input.all end # inside app/views/inputs/index.html.erb <table> <% @inputs.each |input| %> <tr> <td><%= input.title %></td> <td><%= input.content %></td> <td><%= link_to 'show', input %></td> <td><%= link_to 'edit', edit_input_path(input) %></td> <td><%= link_to 'destroy', input, method: :delete, data: { confirm: 'are sure?' } %> </td> </tr> <% end %> </table>
when index
method called, rails will, default, view template of same name method being called; say, search view template called index.html.erb
.
using example i've given here, @inputs
used inside view template has been instantiated index
action called controller.
furthermore, can see instantiation of @inputs
variable:
@inputs = input.all
@inputs
variable references collection of objects database. in other words, inside loop in view template, @ section:
<% @inputs.each |input| %>
each |input|
reference 1 of objects contained inside @inputs
collection, , in turn, each of these objects corresponds database object (i.e. input model). why each input
has attributes called title
, content
, because these defined in database migration columns of input
table.
Comments
Post a Comment