Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top