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

On Tue, May 20, 2008 at 1:59 PM, Scott K. <
[email protected]> wrote:

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


Appreciated my help?
Reccommend me on Working With Rails
http://workingwithrails.com/person/11030-ryan-bigg

Ryan B. 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

On May 20, 7:40 am, Matthew R. Jacobs <rails-mailing-l…@andreas-

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.