Getting column value from lookup table in HABTM relationship

I have a HABTM relationship between my agents and listings tables. Each
listing can have many agents and each agent can have many listings. In
the agents_listings table I have a column called ‘is_primary_agent’
which denotes if the agent is responsible for the listing - only one
agent can be primary.

At the moment I use this in my listing_controller’s view action:
@listing = Listing.find(@params[:id], :include => [ :agents,
:listing_images, :listing_pdfs ] )

What is the best, most efficient way to have this attribute appear
against my agents?

TIA,

Matt.

It sounds like you need to store the primary agent ids in the listings
table, rather than in the join table.

Matthew L. wrote:

I have a HABTM relationship between my agents and listings tables. Each
listing can have many agents and each agent can have many listings. In
the agents_listings table I have a column called ‘is_primary_agent’
which denotes if the agent is responsible for the listing - only one
agent can be primary.

At the moment I use this in my listing_controller’s view action:
@listing = Listing.find(@params[:id], :include => [ :agents,
:listing_images, :listing_pdfs ] )

What is the best, most efficient way to have this attribute appear
against my agents?

TIA,

Matt.

D’oh!

Sorted now, Thanks!

M.

On 5/10/06, Eden B. [email protected] wrote:

If anyone else is following along, I find myself wondering if putting
something like is_primary_agent in the join model is the best approach. The
other option of course would be to just use a habtm and add an attribute to
the listing model called primary_agent_id. Any suggestions?

Definitely preferable to have the primary_agent_id on the listing model.
In the DB there’d be only one record to change when the primary agent
changes (as opposed to two if using a flag) - and there’s no chance of
ending up with multiple agents flagged as primary. The trade off though
is
that you have have to hit both the listing and the agent table to
determine
the primary agent for the listing.

cheers,
Ben

I am not sure I understand your question. Do you want to show the
primary
agent in your list of listings? It seems like you are using a :through
join
model. Is this correct?

Assuming that your join model is called Representations, then couldn’t
you
just do the following:

listing_controller

@primary_agent = @listing.agents.find_by_is_primary_agent(true)

view

Primary Agent: <%= @primary_agent.name %>

I haven’t tried this, but it seems like the right approach.

If anyone else is following along, I find myself wondering if putting
something like is_primary_agent in the join model is the best approach.
The
other option of course would be to just use a habtm and add an attribute
to
the listing model called primary_agent_id. Any suggestions?