Passing a variable to the after_initialize method

I have the following (highly simplified) model that uses will_paginate

class Search < ActiveRecord::Base

  attr_reader :articles

  def after_initialize
    @articles = Article.paginate_by_name name, :page => 1
  end

end

and controller code in my show action

@search = Search.new(params[:search])

Everything works fine, but note that I hardcoded the page number to 1, the problem is passing the value of the [: page] parameter to the after_initialize method, can anyone suggest an elegant way to do this, please?

thank

+3
source share
1 answer

Add a page parameter (or even a better parameter hashing parameter) to the initialization method:

class Search
  def initialize(search, options = {})
    @options = options
  end

  def after_initialize
    @articles = Article.paginate_by_name name, :page => @options[:page]
  end
end

and then in your controller:

@search = Search.new(params[:search], :page => params[:page])

-, .

+6

Source: https://habr.com/ru/post/1754803/


All Articles