2011-12-15 4 views
0

を働いていません。ユーザーはエントリを購読できます。その後、ユーザーは何か他のものを購読することができます。したがって、多形性。Railsの簡単な多型の例では、私は基本的に私のアプリのエントリ、ユーザーとサブスクリプションが今あり、今</p> <p>を私のアプリで多型モデルサブスクリプションを実装する方法を探しています

私は、多形モデルにキャストされたレールに従っています。しかし、私が作ったいくつかの変更:コンソールから

class Subscription < ActiveRecord::Base 
    attr_accessible :user_id, :subscribable_id, :subscribable_type 

    belongs_to :user 

    belongs_to :subscribable, :polymorphic => true 
end 

class Entry < ActiveRecord::Base 
    attr_accessible :title, :body, :img, :author_id 

    belongs_to :author, :class_name => "User", :foreign_key => "author_id" 
    has_many :tidbits 
    has_and_belongs_to_many :tags 

    has_many :subscriptions, :as => :subscribable 
end 

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
end 

# Param: {"subscribable_type": "entry|something", "subscribable_id": int} 
    def create 
    @subscribable = find_subscribable(params[:subscription]) 
    @subscription = @subscribable.subscriptions.build(params[:subscription]) 
    @subscription.user_id = current_user.id 
    if @subscription.save 
     redirect_to :back, :notice => "Successfully created subscription." 
    else 
     redirect_to :back, :notice => "Failed creating subscription." 
    end 
    end 

    def find_subscribable(instance_params) 
    class_name = instance_params["subscribable_type"].classify.constantize 
    class_name.find(instance_params["subscribable_id"]) 
    end 

と私のモデルでは、

1.9.2p290 :037 > Subscription.last 
    Subscription Load (0.1ms) SELECT "subscriptions".* FROM "subscriptions" ORDER BY "subscriptions"."id" DESC LIMIT 1 
=> #<Subscription id: 3, user_id: 1, subscribable_id: 3, subscribable_type: "entry", created_at: "2011-12-15 07:17:53", updated_at: "2011-12-15 07:17:53"> 

どういうわけか、上記のエントリには、サブスクリプションを持っていません

1.9.2p290 :040 > Entry.find(3).subscriptions 
    Entry Load (0.2ms) SELECT "entries".* FROM "entries" WHERE "entries"."id" = ? LIMIT 1 [["id", 3]] 
    Subscription Load (0.2ms) SELECT "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."subscribable_id" = 3 AND "subscriptions"."subscribable_type" = 'Entry' 
=> [] 

私は何をしていますか?ロング?

ユーザーのすべてのエントリのサブスクリプションと他の形式のサブスクリプションにアクセスできるように、ユーザーを設定するにはどうすればよいですか。

+0

どこにいらっしゃいますか?どこの人が助けを必要としているのか分からないとき、どうすれば誰かを助けることができますか? –

+0

@JatinGanhotraあなたは私の投稿を読んだ? 「どういうわけか、上記のエントリにはサブスクリプションがありません。 – disappearedng

+0

@disappearendng:おっと、悪いです。 'cailinanne'が投稿した答えを見てください。ありがとう。 –

答えて

0

2番目のクエリではsubscribable_type = 'Entry'(大文字)が検索されますが、最初のクエリからの出力では、永続化データにはsubscribable_type = 'entry'(小文字)が含まれています。

createメソッドを呼び出すものは、大文字のEntryを渡すように変更する必要があります。

+0

ありがとう。それはそうです! – disappearedng

関連する問題