【问题标题】:Rename foreign_key to override in Rails Convention在 Rails 约定中重命名 foreign_key 以覆盖
【发布时间】:2012-03-30 08:10:56
【问题描述】:

我有两个类之间的关联问题,所以我在这里有一个名为 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

有什么帮助吗?

【问题讨论】:

    标签: ruby-on-rails ruby foreign-keys associations


    【解决方案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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这可能是@Azzurrio 想要的,但它显然没有回答问题。
      • 我根据他提出的问题建议了一个更好的解决方案。我不只是回答问题,而是指出了正确的方向。
      猜你喜欢
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 2018-11-18
      • 2011-09-01
      • 1970-01-01
      相关资源
      最近更新 更多