11175
(-- --)
May 20, 2008, 4:29am
1
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!!!
radar
(Ryan Bigg)
May 20, 2008, 4:39am
2
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
11175
(-- --)
May 20, 2008, 11:40am
3
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
AndyV
(AndyV)
May 20, 2008, 12:13pm
4
: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
11175
(-- --)
May 20, 2008, 3:29pm
5
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.