2012-03-30 3 views
2

나는 두 클래스 사이의 관계에서 문제가를 재정의 foreign_key의 이름을 변경, 그래서 내가 여기에 포스트레일에 협약

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 

라는 클래스 테이블이 있고 다른 하나는 액션

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 

라고 그래서 문제는 내가 Postity 클래스에 외래 키로 target_is를 연관시키고 싶다. 그래서 나는 이것을했다.

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

하지만 작동하지 않습니다, 내가 포스트 객체의 액션 메소드에 Action 객체를 할당하면이 오류가 나타납니다.

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

어떤 도움이 필요합니까?

답변

1

다형성 연관을 적용하려고한다고 가정합니다. 이것을 시험해보십시오.

class Post < ActiveRecord::Base 
has_one :action, :as => :target 
end 

class Action < ActiveRecord::Base 
belongs_to :target, :polymorphic => true 
end 
+0

이 들으 – Azzurrio

+0

이 무엇을 할 수를 @ Azzurrio는 원했지만 분명히 질문에 대답하지 않습니다. – pkoch

+0

나는 그가 물었던 질문에 기초하여 더 나은 해결책을 권고했다. 나는 그 질문에 답하지 않고, 올바른 방향을 가리키고 있었다. –