two issues with foreign attribute

here are my two tables:

ITEMS id name etc...

TOOLS item_id parent_id etc...

tools belongs_to :item

so i can use tool.item.name

but how can i use it in this case for a collection select?

<%= f.collection_select(:parent_id , @tools, :id, :tool.item.name) %>

this obviously won't work but i can't find a solution.

another question i had is order_by a foreign attribute.

how would i do the following?

@tools = Tool.find(:all, :order => tool.item.name)

thanks in advance!!!

You can define a new method in the tool model:

class Tool < ActiveRecord::Base belongs_to :item

def name item.name end end

And then call :name instead of :tool.item.name

Ryan Bigg wrote:

You can define a new method in the tool model:

class Tool < ActiveRecord::Base   belongs_to :item

  def name     item.name   end end

And then call :name instead of :tool.item.name

if you're going to do that, "delegate" is a useful method.

class Tool   belongs_to :item

  def name     item.name   end

  delegate :name, :to => :item end

although, personally I'd prefer no secrets

tool.name feels like a lie tool.item_name is more accurate.

class Tool   belongs_to :item

  def item_name     item.name   end end

:delegate is the way to go because it more clearly demonstrates what you're trying to do, but if you do that then you don't need/want to create an instance method of the same name.

You can also do this:

<%= select :parent, :id, @tools.collect{|tool| [tool.id, tool.item.name]} %> # or tool.name if you delegate

thanks you guys are amazing!!! i have been posting on other rails forums and it would take a week to get a response if i even got one.

i think i found a new favorite forum!!!

all of those are great answers...i'll test some of these out when i get home later tonight.