Rails help looping trough has one and belongs to association -
this kategori controller show action:
def show @kategori = kategori.find(params[:id]) @konkurrancer = @kategori.konkurrancer respond_to |format| format.html # show.html.erb format.xml { render :xml => @kategori } end end
this kategori view show file:
<% @konkurrancer.each |vind| %> <td><%= vind.name %></td> <td>4 ud af 5</td> <td><%= number_to_currency(vind.vaerdi, :unit => "dkk", :separator => ".", :delimiter => ".", :format => "%n %u", :precision => 0) %></td> <td>2 min</td> <td>nyhedsbrev</td> <td><%= vind.udtraekkes.strftime("%d %b") %></td> </tr> <% end %>
my kategori model:
class kategori < activerecord::base has_one :konkurrancer end
my konkurrancer model:
class konkurrancer < activerecord::base belongs_to :kategori end
i want show of konkurrancer have association kategori model
with code following error: nomethoderror in kategoris#show
showing c:/rails/konkurranceportalen/app/views/kategoris/show.html.erb line #12 raised:
undefined method `each' "#":konkurrancer
the problem trying loop on has_one association. has_one means - has one, can't call each on because there one. can 1 of following things solve problem in code:
use has_many association:
class kategori < activerecord::base has_many :konkurrancers end
use has_one association , modify view:
<tr> <td><%= @konkurrancer.name %></td> <td>4 ud af 5</td> <td><%= number_to_currency(@konkurrancer.vaerdi, :unit => "dkk", :separator => ".", :delimiter => ".", :format => "%n %u", :precision => 0) %></td> <td>2 min</td> <td>nyhedsbrev</td> <td><%= @konkurrancer.udtraekkes.strftime("%d %b") %></td> </tr>
which 1 use depends on data model. if kategori have many konkurrancers use first example. if kategori has 1 konkurrancer, use second example. both valid.
Comments
Post a Comment