【问题标题】:newbie: activerecord compare object.count with value throws undefined method `to_sym' for nil:NilClass新手:activerecord 比较 object.count 与 value 为 nil:NilClass 抛出未定义的方法 `to_sym'
【发布时间】:2012-03-05 09:41:34
【问题描述】:
def has_photo

if user_signed_in?

  @user = User.where(:id => current_user.id).first

  if @user.has_photo?
    if Asset.where(:attachable_id => current_user.id).count < 4

      def sub_layout
        "application"
      end

      render :template => "profiles/no_photo"

    end
  end
end

结束

比较 Asset.count 的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 object activerecord compare


    【解决方案1】:

    Asset.where 是一个查询,使用关系会更好。

    如果

    Class User
      has_many :assets
    end
    
    Class Asset
      belongs_to :user
    end
    

    你可以使用:

    @user.assets.count < 4
    

    只要资产具有正确设置的 user_id 字段(或使关系使用 :attachable_id)(如果您正确创建资产,关系也可以这样做)

    顺便说一句,如果 :id 对于每个用户都是唯一的(应该是),你可以重写

    @user = User.where(:id => current_user.id).first
    

    作为

    @user = User.find(current_user.id)
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      相关资源
      最近更新 更多