【问题标题】:Creating a feed => NoMethodError: undefined method for ActiveRecord_Associations_CollectionProxy创建提要 => NoMethodError:ActiveRecord_Associations_CollectionProxy 的未定义方法
【发布时间】:2015-06-14 17:49:52
【问题描述】:

我正在实现属于用户订阅的标签的所有卡片的提要,我收到以下错误。这可能是微不足道的事情,但我无法确定需要做什么。

NoMethodError: undefined method `cards' Tag::ActiveRecord_Associations_CollectionProxy:0x007fbaa46239f8>

这是我的模型:

class User < ActiveRecord::Base
  has_many :cards, dependent: :destroy
  has_many :tags, through: :cards

  has_many :subscriptions, dependent: :destroy 
  has_many :subscribed_tags, through: :subscriptions, source: :tag
end
class Tag < ActiveRecord::Base
  has_many :taggings, dependent: :destroy
  has_many :cards, through: :taggings
  has_many :subscriptions, dependent: :destroy
  has_many :subscribers, through: :subscriptions, source: :user
end
class Card < ActiveRecord::Base
  acts_as_votable
  belongs_to :user
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings    
  def self.tagged_with(name)
    Tag.find_by_name!(name).cards
  end
  def self.tag_counts
    Tag.select("tags.*, count(taggings.tag_id) as count").
    joins(:taggings).group("taggings.tag_id")
  end
  def tag_list
     tags.map(&:name).join(", ")
  end
  def tag_list=(names)
    self.tags = names.split(",").map do |n|
       Tag.where(name: n.strip).first_or_create!
    end
  end
end

我真正想做的是运行 current_user.subscribed_tags.cards 并检索我可以重新排序并作为时间线输出的卡片数组。

谢谢

【问题讨论】:

  • 您要检索 current_user 的标签数组或 current_user 的 subscribed_tags 卡片数组?
  • 糟糕,错字:current_user 的 subscubed_tags 卡片数组

标签: ruby-on-rails rails-activerecord has-many-through model-associations rails-postgresql


【解决方案1】:

subscribed_tags - 它是一个作用域 (where(user: self)),您可以在它们上调用 wherejoin,但不能调用项目方法。

在您的情况下,您想使用scope

class Card
  scope :with_subscription, -> { joins(tags: :subscriptions) }
end

# In controller
current_user.cards.with_subscription.order('cards.created_at DESC')

您可以将current_user.cards 想象成另一种形式的Cards.where(user: current_user)。一旦您告诉您将检索Card 数组 - 它就无法更改。你不能做user.cards.subscriptionsUser.where(id: user).cards.tags 唯一能做的就是过滤器。

接下来我们使用joins(:subscriptions) 进行过滤。它会给我们内部连接,所以我们得到属于有订阅的用户的卡片。这是一个我们可以进一步修改的范围,例如订单。

activerecord join associations

【讨论】:

  • 我得到了一个未定义的方法 with_subscriptions 用于 Card 类,当我考虑额外的“s”时,我仍然得到错误......有什么想法吗?阅读指南后,我真的要查询 RETURN All Cards In 标签,当前用户已订阅
  • 我忘记了冒号。再试一次。
  • 仍然收到错误“意外'{',期待关键字结束范围:with_subscription { joins(:subscriptions) }”如果有帮助的话,我正在使用 rails 4.2.1
  • 我真的不能在这些事情上依赖记忆。再试一次。最终我们会经历这个。
  • 哈哈不用担心,谢谢。我得到一个 activerecord::configurationerror。在卡上找不到名为“订阅”的协会;也许你拼错了?
猜你喜欢
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
  • 2013-03-01
  • 1970-01-01
相关资源
最近更新 更多