Is there a better way to do this in ruby

This actually does not work at all

 @category = Category.find(params[:id])
 @sub_categories = @category.sub_categories
 if @sub_categories
  @designs = []
  @sub_categories.each do |sub_cat|
    @designs << sub_cat.designs.paginate :page => params[:page], :order => 'name', :per_page => @per_page
  end
end

Error with this syntax error

categories_controller.rb:21: syntax error, unexpected tSYMBEG, expecting kEND
...<< sub_cat.designs.paginate :page => params[:page], :order ...

Basically, I have a sub_categories category that has a lot of designs and its current category, and I want to show all the projects for this category ... any idea of ​​best practices and how to fix this problem.

+3
source share
4 answers

I would do two things to reorganize this ...

First, to reduce the connection by moving the pagination parameters to the class method on the design model. Your controller should not know about this model.

class Design < ActiveRecord::Base
  def self.paginate_with_params(params, per_page)
    paginate(:page => params[:page], :order => 'name', :per_page => per_page)
  end
end

Secondly, remove unnecessary variables and logic from your controller that do not really add much value:

@category = Category.find(params[:id])
@designs = @category.sub_categories.map |sub_cat|
  sub_cat.designs.paginate_with_params(params, @per_page)
end

, , , , :)

+2

, @designs, @patterns:

@category = Category.find(params[:id])
@sub_categories = @category.sub_categories
pagination_options = { :page => params[:page],
                       :order => 'name',
                       :per_page => @per_page
                     }
unless @sub_categories.empty?
  @designs = []
  @sub_categories.each do |sub_cat|
    @designs << sub_cat.designs.paginate(pagination_options)
  end
end

, paginate.

+2
a = []
b.each do |c|
    a << c.d(e)
end

It is equal to:

a = b.map { |c| c.d(e) }

And if you ddo not need parameters:

a = b.map &:d

But in your case, I think you just need to add ()around the parameter hash, as Ryan Bigg already answered.

+1
source
@category = Category.find(params[:id])
@sub_categories = @category.sub_categories # assumption: this doesn't return nil
page_opts = {:page => params[:page], :order => 'name', :per_page => @per_page}
@designs = @sub_categories.map {|sub_cat| sub_cat.designs.paginate(page_opts) }
+1
source

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


All Articles