Search code examples
ruby-on-railscontrollernomethoderror

Undefined method '+' for #<Class >


I created a Rails app to allow visitors to read magazines online. I created two scaffolds, one for the magazine itself and one for the pages inside the magazines, that will be scanned images.

The thing is, I use the pages number (an integer) as reference instead of the id, since I want the the magazine's first page's url to look like so : localhost:3000/magazines/magazine-test/1, instead of its ID. So, when uploading a new magazine, I create a loop that increments the pagazine page's number with the help of the loop's index.

Here is my "create" action so that you have a good view of what I'm talking about:

def create
    @magazine = Magazine.new(magazine_params)

    if @magazine.save
      (params[:images] || []).each_with_index do |image, index|
        @magazine.pages.create(image: image, page_number: index + 1)
      end
      redirect_to @magazine, notice: 'Magazine créé'
    else
      render :new
    end
  end

My issue is that if I try to update this magazine and add a few more pages, the page numbers will fall back to 1. So I tried to edit my "update" action as following:

def update
    if @magazine.update(magazine_params)
      if params[:images]
        (params[:images] || []).each_index do |image, index|
          @pages = @magazine.pages.order("page_number DESC").first
          @magazine.pages.create(image: image, page_number: @pages + index + 1)
        abort(@pages)
        end
      end
      redirect_to @magazine, notice: 'Magazine mis à jour'
    else
      render :edit
    end
  end

However, with this method, I get the following error: NoMethodError in MagazinesController#update undefined method '+' for #<Page:0x007fe694b15af8>

I tried a few things (like converting the variable into integer), but I still get this error.

Anyone as an idea ?

Thank you in advance


Solution

  • change this line:

    @magazine.pages.create(image: image, page_number: @pages + index + 1)
    

    to

    @magazine.pages.create(image: image, page_number: @pages.page_number || 0 + index + 1)