简单的has_many无法正常工作

时间:2016-10-15 19:07:23

标签: ruby-on-rails ruby ruby-on-rails-5

我正在努力做一件非常简单的事情。

我希望个人资料与许多评论相关联。现在,如果我尝试在评论中保存,控制台会输出BEGIN,然后立即ROLLBACK表示Euserprofile必须存在。

class EUserProfile < ApplicationRecord
  has_many :EUserRevs
  has_and_belongs_to_many :EUserProfiles,
                          class_name: "EUserProfile",
                          join_table: :e_user_friends,
                          foreign_key: :E_USER_FRIEND_TO,
                          association_foreign_key: :E_USER_FRIEND_FROM

  has_and_belongs_to_many :EUserProfiles,
                          class_name: "EUserProfile",
                          join_table: :e_user_follows,
                          foreign_key: :E_USER_FOLR,
                          association_foreign_key: :E_USER_FOLG
end


class CreateEUserRevs < ActiveRecord::Migration[5.0]
  def up
    create_table :e_user_revs, {:id => false} do |t|
      t.string "E_USER_REV"
      t.string "E_USER_REVING", :null => false
      t.integer "E_USER_SCORE", :null => false
      t.string "E_USER_COMMENT", :null => false

      t.timestamps
    end

  end

  def down

    drop_table :e_user_revs
  end
end

class CreateEUserProfiles < ActiveRecord::Migration[5.0]
  def up
    create_table :e_user_profiles do |t|
      t.string "E_USER_PROFILE_USERNAME", :null => false
      t.string "E_USER_PROFILE_FIRST_NAME", :null => false
      t.string "E_USER_PROFILE_LOC"
      t.string "E_USER_PROFILE_BIO"
      t.string "E_USER_PROFILE_INSTR", :null => false
      t.string "E_USER_PROFILE_GENR", :null => false

      t.timestamps
    end
  end
  def down
    drop_table :e_user_profiles
  end
end

class EUserRev < ApplicationRecord
  belongs_to :EUserProfile
end

1 个答案:

答案 0 :(得分:0)

嗯,这是一个简单的一对多关系。

您需要将以下行添加到CreateEUserRevs迁移文件中:

t.belongs_to : eu_user_profile, index: true

将为EUserRevs架构添加e_user_profile_id字段。 完成后,您可以使用has_many(在EUserProfile模型中)和belongs_to(在EUserRev模型中)。

请记住,ActiveRecord提供的这些帮助程序仅在数据库架构适合时才有效。

您可以阅读有关关联here

的更多信息
相关问题