Some Guy
Some Guy

Reputation: 1511

How do I access a parent table in active record other than the obvious way?

I have a schema and model that I'm stuck with.

It has this association:

  belongs_to :channel, :primary_key => "channel", :foreign_key => "name"

Calling record.channel returns nil. I don't know if that means that channel is a reserved word that I just couldn't track down, or if that's what ActiveRecord does when it's not clear if 'channel' should refer to the field or the table.

I'm able to access the field named channel by using the read_attribute method. Is there a similar method that will enable me to access the Channels class through the given record?

Upvotes: 0

Views: 69

Answers (1)

CDub
CDub

Reputation: 13354

Let's break down this code:

belongs_to :channel, :primary_key => "channel", :foreign_key => "name"

This means that your model (call it Foo) has a foreign key that is the ID of a Channel. So, when you call Foo.first.channel, the SQL generated by the above (since you've provided primary_key and foreign_key) is:

SELECT * FROM channels WHERE channels.channel = <Foo.first>.name

Generally, in a belongs_to, the primary_key shouldn't be set - it will be id on the associated object. Also, generally, best practice is to set up the foreign_key as <associated-model-name>_id. In this case, on the Foo class, it would be channel_id. If it uses this default, neither of those attributes should be necessary.

TL;DR - if Foo has channel_id as a column, your association would simply be:

belongs_to :channel

Upvotes: 1

Related Questions