Rails简单的多态示例不起作用

时间:2011-12-15 08:11:49

标签: ruby-on-rails polymorphism

我基本上正在寻找一种在我的应用程序中实现多态模型订阅的方法

目前我的应用中有条目,用户和订阅。用户可以订阅条目。稍后,用户可以订阅其他内容。因此多态。

我一直在关注多态模型上的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'
 => [] 

我做错了什么?

我该如何设置User以便我可以访问所有用户的条目订阅和其他形式的订阅?

1 个答案:

答案 0 :(得分:0)

iThe第二个查询正在查找subscribable_type = 'Entry'(大写),但第一个查询的输出显示持久数据有subscribable_type = 'entry'(小写)。

您需要更改我们调用create方法的任何内容,以便它传递大写Entry