簡體   English   中英

Rails:arguments 的編號錯誤(給定 1,預期為 0)

[英]Rails : Wrong number of arguments (given 1, expected 0)

我在posts索引頁面上收到此錯誤:

在此處輸入圖像描述

這是 model:

class Post < ApplicationRecord

  include Filterable

  belongs_to :region
  belongs_to :category
  belongs_to :topic
  validates :title, presence: true, length: { maximum: 500 }
  validates :content, presence: true
  validates :published_at, presence: true
  translates :title, :content, :slug, touch: true, fallbacks_for_empty_translations: true
  has_attached_file :image, styles: { thumb: "100x70#", featured: "1560x868#", small: "760x868#", big: ">1600x1600" }
  validates_attachment :image, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }
  validates_attachment_presence :image

  scope :published, -> (published) { where(published: (['true', true].include? published)).order(featured: :desc, published_at: :desc) }
  scope :published_until_now, -> { where("published_at < ?", Time.now).merge(Post.published(true)) }
  scope :topic, -> (topic_id) {
    joins(:topic).where('topic_id = ?', topic_id) }
  scope :category, -> (post_category) {
    joins(:category).where('category_id = ?', post_category) }
  scope :match, -> (search_term) {
    with_translations(I18n.locale).where('content like ? or title like ?', "%#{search_term}%", "%#{search_term}%") }

  self.per_page = 10

  after_save :unfeature_older_posts, if: Proc.new { |post| post.featured? }

  extend FriendlyId
  friendly_id :title, use: :globalize

  def unfeature_older_posts
    featured_posts = Post.where(featured: true).where.not(id: id).order(published_at: :desc)
    if featured_posts.size == 1
      featured_posts.last.update(featured: false)
    end
  end

end

這是 controller:

class PostsController < ApplicationController

  before_action :get_pages_tree, :get_privacy_policy, only: [:index, :show]

  def index
    @filters = params.slice(:topic, :category)
    @posts = Post.published_until_now
      .filter(@filters)
      .paginate(:page => params[:page], per_page: 11)
  end

  def show
    @post = Post.friendly.find(params[:id])
  end
end

filter在這里定義:

module Filterable
  extend ActiveSupport::Concern

  module ClassMethods
    def filter(filtering_params)
      results = self.where(nil)
      filtering_params.each do |key, value|
        results = results.public_send(key, value) if value.present?
      end
      results
    end
  end
end

我不確定 go 從這里到哪里。 我最近在 Rails 5 上升級到 Ruby 和 Ruby 2.7.0,不知道是否相關。

嘗試將module ClassMethods替換為class_methods do

如果有效,請記住:


filter方法來自Ruby。 它在Array中定義。 正如您在 文檔中看到的那樣, Array上的filter方法不帶任何參數。 這是您看到的錯誤的直接原因。

在 Rails 中,當在ActiveRecord object (在您的情況下為Post.published_until_now )上調用Array上的方法並且在 Z20F35E630DAF44DBFA4C3F68F5399D8 上找不到方法時,它會自動將自身轉換為Array 因此,它在Array上調用filter方法。 通常,您不想定義諸如filter之類的令人困惑的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM