2016-07-26 22 views
1

我想篩選我的帖子卻得到了一個錯誤的號碼參數錯誤的(因爲1,預計0)爲什麼我在Rails中的高級查詢中得到錯誤的參數數量錯誤?

我試着基於關閉狀態

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

問題似乎是(至少)有兩個any?方法。首先是Enumerableany?,這正是你想要的。但是,它看起來像實際運行的是ActiveRecordany?。如果至少有一個返回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 
相關問題