【问题标题】:undefined method tag_counts_on for Array数组的未定义方法 tag_counts_on
【发布时间】:2013-07-28 22:32:02
【问题描述】:

我正在使用acts_as_taggable_on gem:https://github.com/mbleigh/acts-as-taggable-on

我正在尝试在某些帖子上显示标签,但它会引发错误:

undefined method `tag_counts_on' for #<Array:0x007fa5d4ac3088>

查看:

<% tag_cloud @vote_feed_items.tag_counts_on(:tags).order('count desc').limit(15), %w[a b c] do |tag, css_class| %>
   <%= link_to tag.name, tag_path(tag.name), class: css_class %>
<% end %>

控制器:

@user = User.find(params[:id])
@vote_feed_items = @user.vote_feed

用户模型:

def vote_feed
  Micropost.unscoped.from_microposts_voted_for_by(self)
end

微邮模型:

def self.from_microposts_voted_for_by(user)
  find_by_sql("select m.* from microposts m
        join (SELECT voteable_id, updated_at FROM votes WHERE voter_id = #{user.id} AND voteable_type = 'Micropost') z on z.voteable_id=m.id
        order by z.updated_at desc")
end

find_by_sql 是否返回一个数组?如果是这样,我需要用不同的方式写这个吗?

【问题讨论】:

    标签: ruby-on-rails acts-as-taggable-on


    【解决方案1】:

    我不确定,但如果你想要返回一个关系,你可以这样做:

    def self.from_microposts_voted_for_by(user)
      results = find_by_sql("select m.* from microposts m
            join (SELECT voteable_id, updated_at FROM votes WHERE voter_id = #{user.id} AND voteable_type = 'Micropost') z on z.voteable_id=m.id
            order by z.updated_at desc")
      Micropost.where id: results.map(&:id)
    end
    

    find_by_sql returns an array.

    使用 ActiveRecord::Relation

    您可以使用关系构建查询,我不确定您的模型,我会假设:

    class Micropost
      has_many :votes
    

    因此您的方法将与范围内的 Rails 更加一致:

    scope(:voted_by, ->(user) do
      joins(:votes).where('votes.voter_id = ?', user.id).order('votes.updated_at desc')
    end)
    

    您也不会急切地访问数据库。你可以使用这个作用域:

    @microposts = Micropost.voted_by current_user
    

    【讨论】:

    • 非常感谢您的帮助。我是 ruby​​ 和示波器的新手,干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多