有人可以找到“未知属性”我的语法/逻辑错误是一个多对多的种子创建方法时,在Rails的连接表?

问题描述 投票:0回答:2

该项目是建立一个web应用程序,我将用它来记录和跟踪我的力量训练课。其中一个表/模型是连接演习和训练的正文部分连接表。

下面是练习表迁移:

# 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

下面是表的种子数据:

# 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

这里是我的种方法来填充数据库:

# 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

以下是错误信息:

# error message:
ActiveModel::UnknownAttributeError: unknown attribute 'exercise' for ExerciseBodypart.
ruby-on-rails postgresql activerecord foreign-keys jointable
2个回答
1
投票

我不知道确切的原因,但它是为我工作在rake rails-3任务内,但失败rails-5同时更新应用到更高的版本。

我建议你试试以下,以下为我工作,

exercise_id: Exercise.find_by_name(ex_body[:name]).id

0
投票

我从另一个Ruby开发谁说我应该是命名与belongs_to模型的关系性质的咨询意见

我确实做到了和逻辑工程确定。

我的模型看起来是这样的:

class ExerciseBodypart < ApplicationRecord
  belongs_to :exercise
  belongs_to :bodypart
end

你瞧,这是关键。这espressed模型在我的其他项目不存在关系;但我怀疑,我们的关系从其他型号的连接取 - 因为它是多了很多的模型更复杂的数据库。

© www.soinside.com 2019 - 2024. All rights reserved.