Rails: неверное количество аргументов (дано 1, ожидается 0) - PullRequest
0 голосов
/ 20 апреля 2020

Я получаю эту ошибку на моей posts странице индекса:

enter image description here

Эта модель:

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

Эта контроллер:

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 отсюда. Я недавно обновился до Ruby на Rails 5 и Ruby 2.7.0, я не знаю, связано ли это.

1 Ответ

4 голосов
/ 20 апреля 2020

Попробуйте заменить module ClassMethods на class_methods do.

Если это сработает, то имейте в виду:


filter метод происходит от Ruby. Это определено в Array. Как вы можете видеть в do c, метод filter для Array не принимает аргументов. Это прямая причина ошибки, которую вы видите.

В Rails, когда методы на Array вызываются на ActiveRecord объекте (в вашем случае, Post.published_until_now) и когда методы не могут быть найдены в модели , он автоматически преобразуется в Array. Итак, он вызывает метод filter для Array. Как правило, вы не хотите определять методы, такие как filter, что сбивает с толку.

...