Reputation: 11421
Intro:
I am working on a car dealer project.. sells every brand of cars from A to Z. I would like to make little box with links for each carname. Clicking on Mercedes for ex, will render all the mercedes cars and so on for all the cars. Here is what I have right now:
in cars controller
def mercedes
...
@cars = Car.where('carname_id = 1').order('created_at desc').paginate :page => params[:page], :per_page => 5
end
and a code like this for each car, 30 pieces.. but there will be more in view I have
<%= link_to 'Mercedes', :controller => :cars, :action => :mercedes %>
also about 30 lines of this code, one for each car. and beside this I mus have 30 views files.. well, with views I guess I can use one partial for all cars
The problem:
How can this be done in a less code. And may be it will help.. I have a table named carnames where I keep all the cars so I cold do something like
<% @carnames.each do |car| %>
<%= link_to '<%= carname.name %>', :controller => :cars, :action => :<%= carname.name %> %>
<% end %>
and I think this will generate the links to each cars for me withous writing them, the problem them is in controller.. I'm not sure if it's ok to write this amount of code. I hope I make it clear. Thanks for your time.
EDIT
here is how my cars are stored:
I keep carnames in a table called carnames and models in carmodels.. each table have an ID field and name field.. so Meredes E class for ex will have the carname from carname tables with specific id_carname and E class from carmodel table with specific id_carmodel.. I have all the belongs_to and has_many in place for all models.
Upvotes: 1
Views: 55
Reputation: 6840
You're having trouble because you're doing it wrong. Having a controller action called "mercedes" rings alarm bells. Ideally you'd have a Brand model/controller, which has_many cars. For example:
class BrandsController < ApplicationController
def show
@brand = Brand.find params[:id]
end
end
class CarsController < ApplicationController
def index
@brand = Brand.find params[:brand_id]
@cars = @brand.cars.paginate(:page => params[:page], :per_page => 5)
end
end
class Brand < ActiveRecord::Base
has_many :cars
# With this, your car URL could be /brands/1-mercedes/cars,
# instead of just /brands/1/cars.
def to_param
"#{self.id}-#{self.name}"
end
end
class Car < ActiveRecord::Base
belongs_to :brand
end
resources :brands do
resources :cars
end
<h1><%= @brand.name %></h1>
<% @cars.each do |car| %>
<%= link_to car.name, [@brand, car] %>
<% end %>
For reference, you'd use carname.name.to_sym
, like so:
<% @cars.each do |car| %>
<%= link_to car.name, :controller => :cars, :action => car.name.to_sym %>
<% end %>
Though passing the car
record should be sufficient:
<% @cars.each do |car| %>
<%= link_to car.name, car %>
<% end %>
However this doesn't change that you're writing bad code.
Upvotes: 4