Reputation: 461
The project is to build a web-app which I will use to log and track my strength training sessions. One of the tables/models is a join table linking exercises and trained bodyparts.
Here is the migration for the exercise table:
# migration: successfully creates the join table
class CreateExerciseBodyparts < ActiveRecord::Migration[5.2]
def change
create_table :exercise_bodyparts do |t|
t.references :exercise, foreign_key: true
t.references :bodypart, foreign_key: true
t.timestamps
end
end
end
Here is the seed data for the table:
# seed data snippet: no syntax errors here
def exercise_bodyparts_list
return [
{
name: "Barbell Back Squats",
bodyparts: ["Quads","Hamstrings","Adductors","Abductors","Glutes","Lower Back","Abs"]
},
{
name: "Barbell Biceps Curls ~0°",
bodyparts: ["Biceps","Forearms"]
},
{
name: "Barbell Biceps Curls ~45°",
bodyparts: ["Biceps","Forearms"]
},
#(...)
]
end
Here is my seed method to populate the DB:
# seed method: where the error comes...
exercise_bodyparts_list.each do |ex_body|
ex_body[:bodyparts].each do |bodypart|
ExerciseBodypart.create!(
exercise: Exercise.find_by_name(ex_body[:name]),
bodypart: Bodypart.find_by_name(bodypart)
)
end
end
Here is the error message:
# error message:
ActiveModel::UnknownAttributeError: unknown attribute 'exercise' for ExerciseBodypart.
Upvotes: 0
Views: 35
Reputation: 461
I received advice from another Ruby developer who said that I ought to be naming the relationship nature in the model with belongs_to
I indeed did that and the logic works ok.
My model looks like this:
class ExerciseBodypart < ApplicationRecord
belongs_to :exercise
belongs_to :bodypart
end
Lo and behold, this was the key. This espressed relationship in the model doesn't exist in my other project; however I suspect that the relationship is taken from the connection of other models - as it is a more complicated database with many more models.
Upvotes: 0
Reputation: 5552
I do not know exact reason but it was working for me inside rake
task in rails-3
but failed for rails-5
while updating application to higher version.
I suggest you try following, following worked for me,
exercise_id: Exercise.find_by_name(ex_body[:name]).id
Upvotes: 1