Reputation: 618
I have two objects:
create_table "conditions", force: true do |t|
t.string "name"
t.integer "condition_category_id"
end
create_table "condition_categories", force: true do |t|
t.string "name"
end
I am trying to list my conditions with the condition category name in another column. However since I named it with an underscore I am a bit confused on how to properly set up the association. I noticed that the model was rewritten to ConditionCategory, but I still can't get it working right.
Here is my model for Condition
class Condition < ActiveRecord::Base
belongs_to :category, class_name: 'ConditionCategory'
end
And on my view
<td><%= condition.category.name %></td>
Relatively new to rails so any help is much appreciated
Upvotes: 2
Views: 117
Reputation: 33552
You have two options.
1.As @gregates suggested you should add foreign_key
to your association in your Condition
model
class Condition < ActiveRecord::Base
belongs_to :category, class_name: 'ConditionCategory',
foreign_key: 'condition_category_id'
end
OR
2.Just modify your Condition
model like this.Which is very simple and precise.
class Condition < ActiveRecord::Base
belongs_to :condition_category
end
And in your view,you have to change like this
<td><%= condition.condition_category.name %></td>
to get the name of the condition_category
associated with that condition
Upvotes: 2
Reputation: 6724
See the foreign_key
option for the belongs_to
relation. The foreign key is expected to match the name of the association, not the class_name
(when they differ). So you need to specify both:
belongs_to :category, class_name: 'ConditionCategory',
foreign_key: 'condition_category_id'
Alternatively, you can rename the foreign key column in the database to category_id
.
Upvotes: 1