2009-06-14 5 views
0

has_ ​​many_ polymorphs ActiveRecord 플러그인을 사용하여 양면 다형성 관계의 간단한 예제로 작업합니다. 나는 "고양이"와 "개"라는 두 가지 클래스를 가지고 있는데, 이들은 서로 "우정"을 가질 수 있으므로 "고양이", "개"및 "우정"의 세 가지 클래스가 있습니다. 고양이는 개와 친구가 될 수 있습니다 (예, 일어납니다!) 물론 다른 고양이와도. 개를 위해 동일은 간다. 여기 내 모델입니다 :이 작업을 얻기 위해 일하려고했는데has_many_polymorphs CRUD 매개 변수를 올바르게 설정하는 방법

class Cat < ActiveRecord::Base 
    validates_presence_of :name 
end 

class Dog < ActiveRecord::Base 
    validates_presence_of :name 
end 

class Friendship < ActiveRecord::Base 
    belongs_to :left, :polymorphic => true 
    belongs_to :right, :polymorphic => true 

    acts_as_double_polymorphic_join(
    :lefts => [:cats, :dogs], 
    :rights => [:dogs, :cats] 
) 
end 

내가 뭔가를 분명 실종해야합니다. 나는 새로운 친구를 만들려고 할 때 내가 얻을 : 나는 새로운 "우정"을 만들기 위해 노력하고

ActiveRecord::Schema.define(:version => 20090613051350) do 
    create_table "cats", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 
    create_table "dogs", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 
    create_table "friendships", :force => true do |t| 
    t.integer "left_id" 
    t.string "left_type" 
    t.integer "right_id" 
    t.string "right_type" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 
end 

:

NameError (wrong constant name cats): 
    (eval):7:in `before_save' 
app/controllers/friendships_controller.rb:45:in `create' 

또는

NameError (wrong constant name dogs): 
    (eval):7:in `before_save' 
app/controllers/friendships_controller.rb:45:in `create' 

내 schema.rb입니다 URL에서 left_ type 및 left_ id를 얻고 POST 매개 변수에서 right_ type 및 right_ id를 얻는 경로를 사용하여/cats/3/relationships과 같은 POST를 작성합니다. 라우팅 올바르게 friendships_ 컨트롤러의 # 만들기 방법을 트리거하고 결과 PARAMS는 다음과 같습니다 : 나는 "왼쪽, 오른쪽으로"와 "권리"의 사이에 분리 할이 질문의 범위를 벗어난 이유로

Parameters: { 
    "authenticity_token"=>"gG1eh2dXTuRPfPJ5eNapeDqJu7UJ5mFC/M5gJK23MB4=", 
    "left_type"=>"cats", 
    "right_type"=>"dogs", 
    "left_id"=>"3", 
    "right_id"=>"1" 
} 

내가 우정이 게시 된 사람 (따라서 "왼쪽"과 "권리")을 추적 할 수있는 그런 방식으로, 그러나 아마도 내 모델은 이것을 달성하기위한 올바른 방법이 아닙니까? has_ many_ polymorphs 플러그인의 목적을 오해 했습니까?

def create 
    @friendship= Friendship.new(
    :left_type => params[:left_type], 
    :left_id => params[:left_id], 
    :right_type => params[:right_type], 
    :right_id => params[:right_id] 
) 
    respond_to do |format| 
    if @friendship.save 
     format.xml { 
     render :xml => @friendship, 
     :status => :created, 
     :location => @friendship 
     } 
    else 
     format.xml { 
     render :xml => @friendship.errors, 
     :status => :unprocessable_entity 
     } 
    end 
    end 
end 

그리고 마지막으로 내 routes.rb : 내가 말했듯이

map.resources :friendships 

map.resources :cats do |cat| 
    cat.resources :friendships, :path_prefix => "/:left_type/:left_id" 
end 

map.resources :dogs do |dog| 
    dog.resources :friendships, :path_prefix => "/:left_type/:left_id" 
end 

, 나는이 그림을 시도하는 내 자신에 긴 시간을 보냈어요 여기에 # 만들기의 friendships_ 컨트롤러의 조치입니다 하지만 문서가 오래되었거나, 너무 일반적이거나, 너무 진보적 ​​인 경우 또는 경우에 따라 동시에 세 가지가 있습니다. 이 RoR 물건을 시작하는 것은 쉽지 않습니다, 나는 말할 수 있습니다! 나는 RoR 숙달의 진정한 이점이 있다는 것을 알고 있으므로 계속 사용 하겠지만,이 헤드 스태프 중 일부는 너무 나빠서 대머리 패치를 받기 시작합니다. 나는 경험 많은 Ruby/Rails devs가 많이 있다는 것을 알고 있으며 누군가가 목공예품에서 나와서 이것을 우리에게 단순한 필사자로 설명하기를 희망합니다. 사전에

감사합니다,

JS

답변

0

고양이와 개가 돼지와 친구이고 누가 우정을 시작했는지 알고 싶다면 다형성 관계가 필요한 대부분의 것을해야합니다. 이전의 해결책은 너무 단순합니다.

class Animal < ActiveRecord::Base 
    belongs_to :creatures, :polymorphic => true 
    named_scope :cats, :conditions => {:creature_type => 'Cat'} 
    named_scope :dogs, :conditions => {:creature_type => 'Dog'} 
    named_scope :pigs, :conditions => {:creature_type => 'Pig'} 
end 

class Cat < ActiveRecord::Base 
    has_many :friends, :as => :creatures 
end 

class Dog < ActiveRecord::Base 
    has_many :friends, :as => :creatures 
end 

class Pig < ActiveRecord::Base 
    has_many :friends, :as => :creatures 
end 

당신이 원하는하지 않을 수 있지만, 당신이 할 수 있도록 has_many 연결을 추가 할 수 있습니다 당신은 등 cat.friends 및 cat.friends.dogs, cat.friends.pigs

를 호출 할 수 것입니다 cat.dogs 및 cat.pigs를 직접 호출하십시오.

class Cat < ActiveRecord::Base 
    has_many :friends, :as => :creatures 
    has_many :dogs, :through => :animal 
    has_many :pigs, :through => :animal 
end 

내가 찾고있는 것이 맞는지 확실하지 않지만 간단하고 쉬운 방법이라고 생각합니다.

0

나는 아마 고양이와 개 모델을 선택하고 다음 has_and_belongs_to_many 연결을 사용하는 거라고? (가) 테이블과 같을 것이다 가입 그런

class Cat < ActiveRecord::Base 
    has_and_belongs_to_many :dogs 
end 

class Dog < ActiveRecord::Base 
    has_and_belongs_to_many :cats 
end 

...

create_table "cats_dogs", :id => false, :force => true do |t| 
    t.integer "cat_id" 
    t.integer "dog_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

당신은 어떤 찾을 cat.dogs 및 dog.cats를 호출 할 수있을 것 '우정을.'

+0

제임스 감사합니다. 훨씬 간단 해 보입니다. 하지만 두 개 이상의 기본 클래스가있을 때 조금 어색해지기 시작하지 않겠습니까? 돼지들에게 제 3의 클래스를 추가하는 것은 다른 두 사람에게 달린 것입니까? 또한이 모델은 어떤 관계자가 관계의 창시자인지 (위의 예에서 "왼쪽") 볼 수 없거나 내가 오해하고 있습니까? –

관련 문제