2011-12-15 23 views
0

我基本上是在尋找一種方式,我的應用程序來實現多態模型認購,現在Rails的簡單的多態例如不工作

有條目,用戶和訂閱我的應用程序現在。用戶可以訂閱條目。稍後,用戶可以訂閱其他內容。因此是多態的。

我一直在關注鑄造多態模型的鐵軌。不過,我已經做了一些修改:

# 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 

,並在我的模型:

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 

從控制檯:

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' 
=> [] 

我在做什麼w榮?

我應該如何設置用戶,以便我可以訪問所有用戶的條目訂閱和其他形式的訂閱?

+0

你卡在哪裏?當他/她不知道你需要幫助的時候,有人能幫助你嗎? – 2011-12-15 10:51:45

+0

@JatinGanhotra你看過我的帖子了嗎? 「不知何故,上面的條目沒有訂閱:」哪部分似乎沒有「卡住」給你? – disappearedng 2011-12-16 01:13:05

回答

0

i第二個查詢是查找subscribable_type = 'Entry'(大寫),但第一個查詢的輸出顯示持續數據有subscribable_type = 'entry'(小寫)。

您需要更改我們所說的create方法,使其通過大寫Entry