After scouring these forums, the blogs, & wiki’s I’ve finally decided to
ask the question because either nobody has encountered this problem or,
more likely, I I’m missing something obvious.
I am attempting to access the extra attributes on the join model through
a has_many :through association. Most code examples I have found don’t
deal with this situation even though, I think, that was part of decision
to deprecate HABTM in favor of HMT.
I have tables “accounts”, “links”, and the join table “account_links”.
In the end, I want to be able to do this:
a = Account.find(1)
a.links[0].label
=> “untitled”
The closest I’ve been able to get is:
a = Account.find(1)
a.links[0].account_links[0].label
=> “untitled”
The closest solution I found was at
Join table attributes piggy backed with has_many through - Rails - Ruby-Forum but I could not get it to work.
The poster never replied back if the solution worked for them.
-TABLES-
create_table :accounts do |t|
t.column :email_address, :string, :limit => 40, :null => false
t.column :password, :string, :limit => 40, :null => false
t.column :created_at, :datetime, :null => false
end
create_table :links do |t|
t.column :url, :text, :null => false
t.column :created_at, :datetime
end
create_table :account_links do |t|
t.column :account_id, :integer, :null => false
t.column :link_id, :integer, :null => false
t.column :label, :string, :limit => 20, :null => true
end
-MODELS-
class Account < ActiveRecord::Base
has_many :account_links
has_many :links, :through => :account_links
end
class Link < ActiveRecord::Base
has_many :account_links
has_many :account, :through => :account_links
end
class AccountLink < ActiveRecord::Base
before_create :set_label
belongs_to :account
belongs_to :link
def set_label
write_attribute(“label”, ‘untitled’)
end
end
Thanks for any guidance.