Topic: Avoid smelly code

Hi everyone,

In my project I have different types of reviews, e.g. cd reviews, concert reviews and so on. Now when creating these reviews I use a collection_select in the views to get an artist dropdown. My problem is: There are many ways to grab the artists:

<%= collection_select :band_review, :artist_id, Artist.find(:all), :id, :name %>

this looks pretty ugly to me...

Next idea:

<%= collection_select :band_review, :artist_id, @artists, :id, :name %>

and in the controller:
@artists = Artist.find(:all)

I guess this is ok but since I have several types of reviews I will have to put this code into every controller.

Last idea: Use the application_helper.rb so I can use this method in every view:

  def find_all_artists
    return Artist.find(:all)

Well, simple code, but what

Re: Avoid smelly code

Looks like you're on the right track. All three options are acceptable IMO. An alternative is to create a class method in the model for doing the find.

# view
<%= collection_select :band_review, :artist_id, Artist.find_alphabetical, :id, :name %>

# artist model
def self.find_alphabetical
  find(:all, :order => 'name')

Of course rename it to your liking and change the find parameters.

Railscasts - Free Ruby on Rails Screencasts

Re: Avoid smelly code

Thanks ryanb,

I was just wondering whether any of my ideas is violating the mvc pattern. I

Re: Avoid smelly code

Accessing the model directly from the view does not violate MVC in any way IMO.

Railscasts - Free Ruby on Rails Screencasts

Re: Avoid smelly code

I just would stay away from doing any thing more than accessing instance or singleton methods.

Rails, Javascript, Actionscript and More.