重命名foreign_key以在Rails约定中重写



我在两个类之间的关联中遇到问题,所以我在这里有一个名为Post 的类表

Class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
        t.string :post_type , null: false
        t.text :content , null: false
        t.integer :person_id
    end
    add_index :posts, :person_id
    add_index :posts, :group_id
  end
end

另一个叫做Action

class CreateActions < ActiveRecord::Migration
  def change
    create_table :actions do |t|
        t.string :target_type, null:false
            t.integer :target_id
        t.integer :upvote_count
      t.timestamps
    end
      add_index :actions,:target_id
  end
end

所以问题是我想将target_is作为外键与Post类相关联,所以我做了这个

class Post < ActiveRecord::Base
    has_one :action
end
class Action < ActiveRecord::Base
    belongs_to :post , :class_name => 'Target', :foreign_key => 'target_id'
end

但它不起作用,当我将Action对象分配给Post对象中的Action方法时,这个错误出现在中

Mysql2::Error: Unknown column 'actions.post_id' in 'where clause': SELECT  `actions`.* FROM `actions`  WHERE `actions`.`post_id` = 6 LIMIT 1

有什么帮助吗?

您需要在关联的两侧设置外键:

class Post < ActiveRecord::Base
    has_one :action, :foreign_key => 'target_id'
end
class Action < ActiveRecord::Base
    belongs_to :post , :class_name => 'Target', :foreign_key => 'target_id'
end

http://guides.rubyonrails.org/association_basics.html#has_one-关联参考

http://guides.rubyonrails.org/association_basics.html#belongs_to-关联参考

我想您正在尝试应用多态关联。试试这个。

class Post < ActiveRecord::Base
has_one :action, :as => :target
end
class Action < ActiveRecord::Base
belongs_to :target, :polymorphic => true
end

最新更新