我在两个类之间关联时遇到问题,所以我这里有一个名为 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 对象中的操作方法时,会出现此错误
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-association-reference
http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference
关于ruby-on-rails - 重命名foreign_key以在Rails约定中覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9939214/