INTRO
model A
carname.rb
class Carname < ActiveRecord::Base
belongs_to :car
has_many :carmodels, :dependent => :destroy
...
model B
carmodel.rb
class Carmodel < ActiveRecord::Base
belongs_to :carname
belongs_to :car
...
carname fields: id, name
carmodel fields: id, name, carname_id
The problem:
I add a car name for ex BMW, then I can add carmodels for ex 3 series and select that this belongs to BMW. Works good in different views, but I want it to display the carmodels in the index view of carname, something like this
in http://www.whateverdomain.com/carnames
BMW
3 series
5 series
7 series
Mercedes
E class
S class
C class
I have carnames displayed, not a big deal:
<% @carnames.each do |carname| %>
<%= carname.name %>
<% end %>
but I can’t think off how to add models nex to it.
In carmodels index view I managed to display each carmodels with the carname that it belongs_to next to the carmodel
<% @carmodels.each do |carmodel| %>
<%= carmodel.name %>
<%= carmodel.carname.name %>
<%= link_to 'Edit', edit_carmodel_path(carmodel) %>
<%= link_to "Delete", carmodel, :confirm => 'Are you sure?', :method => :delete %>
<% end %>
so in this html on screen looks like
3 series | BMW
5 series | BMW
7 series | BMW
C class | Mercedes
E class | Mercedes
etc..
if any other info is needed I’ll share it. Thank you for your time.
Try this code in your carnames/index.html.erb file:
It will add every carname and their car models as an unordered list.
Edit: If you want to display carmodel.name | carname.name you can do:
Note: Why does a Carname belong to a Car? Wouldn’t it be easier to assign a name attribute to the Car class?