2012-01-16 11 views
0

次のモデル(Rails 3.2rc1)にはごく小さな問題があります。オーナーシップは、プロジェクト(Projects)とブログ(Blogs)をユーザー(所有者)にマッピングすることで、オーナーシップを異なる方法で扱うさまざまな種類のブログが存在します。has_many:1つのポリモーフィック・クラスとサブクラス化されたレッグ・ビーブブとの関係

class User < ActiveRecord::Base 
    has_many :ownerships, dependent: :destroy 
    has_many :projects, through: :ownerships, source: :ownable, :source_type => 'Project' 
    has_many :site_blogs, through: :ownerships, source: :ownable, :source_type => 'SiteBlog' 
end 

class Ownership < ActiveRecord::Base 
    belongs_to :ownable, polymorphic: true 
    belongs_to :owner, :class_name => 'User', foreign_key: 'user_id' 
end 

class Project < ActiveRecord::Base 
    has_many :owners, through: :ownerships, as: :ownable 
    has_many :ownerships, as: :ownable, dependent: :destroy 
end 

class Blog < ActiveRecord::Base 
end 

class SiteBlog < Blog 
    has_many :owners, through: :ownerships, as: :ownable 
    has_many :ownerships, as: :ownable, dependent: :destroy 
end 

class ProjectBlog < Blog 
    belongs_to :project 
end 

それはすべて、これまで正常に動作しますが、SiteBlog#owners誤動作だけ:"ownable_type" = 'Blog'

SiteBlog.first.owners 
    SiteBlog Load (0.8ms) SELECT "blogs".* FROM "blogs" WHERE "blogs"."type" IN ('SiteBlog') LIMIT 1 
    User Load (1.4ms) SELECT "users".* FROM "users" INNER JOIN "ownerships" ON "users"."id" = "ownerships"."user_id" WHERE "ownerships"."ownable_id" = 231145885 AND "ownerships"."ownable_type" = 'Blog' 
=> [] 

問題が発生したSELECTの最後です。これがうまくいくためには、それは"ownable_type" = 'SiteBlog'でなければなりませんが、ARELに教える方法はわかりません。

アイデア?

答えて

0

あなたの例に基づいて小さなレールアプリを作成しました。それはうまく動作します。

User.create 
SiteBlog.create 
SiteBlog.first.owners << User.first 

あなたはownable_typeは "SiteBlog"、 "ブログ" ではありません見ての通りこれは、所有権レコード

#<Ownership id: 5, ownable_id: 5, ownable_type: "Blog", user_id: 5, created_at: 2012-01-17 20:14:01", updated_at: "2012-01-17 20:14:01"> 

を作成します。次に:

SiteBlog.first.owners 
SiteBlog Load (0.3ms) SELECT "blogs".* FROM "blogs" WHERE "blogs"."type" IN ('SiteBlog') LIMIT 1 
User Load (0.3ms) SELECT "users".* FROM "users" INNER JOIN "ownerships" ON "users"."id" = "ownerships"."user_id" WHERE "ownerships"."ownable_id" = 5 AND "ownerships"."ownable_type" = 'Blog' 
=> [#<User id: 5, created_at: "2012-01-17 19:44:45", updated_at: "2012-01-17 19:44:45">] 

したがって、クエリが機能しています。

そして、ここに主要な部分があります。 ActiveRecordの/ libに/のActiveRecord /団体/ association.rbを見てください:

def creation_attributes 
    attributes = {} 

    if reflection.macro.in?([:has_one, :has_many]) && !options[:through] 
    attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key] 

    if reflection.options[:as] 
     attributes[reflection.type] = owner.class.base_class.name 
    end 
    end 

    attributes 
end 

具体的に、この行はRailsは、基本クラスの名前を書くことになっていることを伝える - それはブログ、未SiteBlogです:

ので
attributes[reflection.type] = owner.class.base_class.name 

あなたの例とRailsの動作ではすべてがうまくいくようです。

+0

これはちょっと恥ずかしいことです:-)実際には、試用版アプリケーションで問題の原因となっていました。このためのスペックを書く時間。 – svoop

関連する問題