我正在尝试过滤我的帖子,但错误的参数数量错误(给定1,预期为0)
我试图根据条件过滤它们
if current_user.courses.any? {|h| h[:name] == post.course.name}
这是索引
的控制器操作def index
@posts = Post.all(:joins => :course, :conditions => "courses.name in (#{@user.courses.map(&:name).join(',')})",:order => "posts.created_at DESC")
end
以下是我的模特
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :course
has_many :comments
end
class Course < ActiveRecord::Base
belongs_to :user
has_many :posts
belongs_to :major
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :courses
belongs_to :major
has_many :posts
has_many :comments
accepts_nested_attributes_for :courses, reject_if: :all_blank, allow_destroy: true
end
谢谢!
答案 0 :(得分:0)
问题似乎是(至少)有两种any?
方法。首先是Enumerable
any?,这正是您所希望的。但是,看起来实际运行的是ActiveRecord
any?。第一个遍历您提供的块,如果至少有一个返回true则返回。第二个不带任何参数,并告诉您是否存在任何记录。
根据您的需要,我会将您的代码更改为:
#This converts courses to an array
if current_user.courses.to_a.any? {|h| h[:name] == post.course.name}
OR
#This uses the method select instead
if current_user.courses.select{|h| h[:name] == post.course.name}.count > 0