0

jira という別のフォルダー (instance.rb、generic_field.rb など) にいくつかのモデルがあります。それらはすべて JIRA の下でネームスペース化されています。たとえば、JIRA::Instance < ActiveRecord::Base、JIRA::GenericField < ActiveRecord::Base です。以下に 2 つのモデルを示します。

class JIRA::GenericField < ActiveRecord::Base
  self.table_name = "jira_generic_fields"
  belongs_to :jira_instance, class_name: JIRA::Instance
end


class JIRA::Instance < ActiveRecord::Base
  self.table_name = "jira_instances"
  has_many :jira_generic_fields, dependent: :destroy, class_name: JIRA::GenericField
end

テーブルの DB スキーマ:

create_table "jira_generic_fields", force: true do |t|
  t.string  "jira_id"
  t.string  "name"
  t.integer "jira_instance_id",      null: false
end

create_table "jira_instances", force: true do |t|
  t.string "jira_link"
  t.string "crowd_link"
end

Rails コンソールで JIRA::Instance オブジェクトを作成し、それを破棄しようとすると、次のようになります。

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'jira_generic_fields.instance_id' in 'where clause': SELECT `jira_generic_fields`.* FROM `jira_generic_fields`  WHERE `jira_generic_fields`.`instance_id` = 1

ActiveRecord が を使用する理由jira_generic_fieldsinstance_idの代わりにjira_generic_fields。モデルを同じ名前空間jira_instance_idに保持しながら、これを修正するにはどうすればよいですか?JIRA

4

1 に答える 1

1

最後に、モデルでforeign_keyを指定すると、これが解決されました...

class JIRA::GenericField < ActiveRecord::Base
  self.table_name = "jira_generic_fields"
  belongs_to :jira_instance, foreign_key: 'jira_instance_id', class_name: JIRA::Instance
end

class JIRA::Instance < ActiveRecord::Base
  self.table_name = "jira_instances"
  has_many :jira_generic_fields, dependent: :destroy, foreign_key: 'jira_instance_id', class_name: JIRA::GenericField
end

私はそれがあまり好きではありませんが、今のところそうしなければなりません。

于 2015-03-24T15:22:05.970 に答える