Reputation: 1167
Not sure if I'm doing this right. Have two models:
class Team < ActiveRecord::Base
attr_accessible :city, :name, :division_id
belongs_to :divison
has_many :players
end
class Division < ActiveRecord::Base
attr_accessible :name
has_many :teams
end
And the migration for :teams includes a foreign_key
create_table :teams do |t|
t.string :name
t.string :city
t.integer :division_id
t.foreign_key :division, dependent: :delete
t.timestamps
end
In my Teams
index view, I'd like to add the division
name for each team. Getting the id is simple, I just use <%= team.division_id %>
However, I'm not sure what to do to get the division name.
I tried adding the division to each team:
@teams.each do |team|
team.division = Division.find(team.division_id)
end
But this failed, saying: undefined method 'division=' for #<Team:0x3cf2df0>
. I'm not even sure if this is the right way to go about doing this, or if I'm over-complicating things.
Upvotes: 0
Views: 99
Reputation: 230306
Since you have the relation, you should be able to just do
team.division.name
Also, you have a typo in your model (you would have never missed this kind of error in a statically typed language like Java. In Ruby you have to write tests, lots of tests)
belongs_to :divison
Upvotes: 2