Friday, July 29, 2016

How to sum attributes of the model in Rails by date? | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

How to sum attributes of the model in Rails by date? | Fixed issues


How to sum attributes of the model in Rails by date?

Posted: 29 Jul 2016 08:33 AM PDT

I have a model Entry with attribute cal and date. I also have a User model with an attribute expected_cal (expected calories) I need to sum cal by each date and if sum is less than expected_cal all records in the index.html.erb should become green, otherwise - red.

index.html.slim

h1 Listing entries    table.table    thead      tr        th Date        th Time        th Content        th Cal        th User        th        th        th      tbody      - if can? :manage, Entry        - @entries.each do |entry|          tr(class=expected_calories_class(current_user, @sum_cal))            td = entry.date            td = entry.time.strftime("%H:%M")            td = entry.content            td = entry.cal            td = entry.user.role            td = link_to 'Show', entry            td = link_to 'Edit', edit_entry_path(entry)            td = link_to 'Destroy', entry, data: { confirm: 'Are you sure?' }, method: :delete    br    = link_to 'New Entry', new_entry_path  

entries_controller.rb

def index  @entries = Entry.where(user_id: current_user.id).group_by(&:date)  @user = current_user  @sum_cal = Entry.group(:date).sum(:cal)  if @user.role == 'admin'    @entries = Entry.all    @sum_cal = Entry.group(:date).sum(:cal)  end  

end

entries_helper.rb

module EntriesHelper  def expected_calories_class(user, entry)    if user.expected_cal <= entry.cal      'unexpected-calories'    else      'expected-calories'    end  end  

end

entries.scss

.expected-calories {    background: green;  }  .unexpected-calories {    background: red;  }  

How do I check to an array of objects with the parameter start_at, which is a Datetime is before DateTime.now

Posted: 29 Jul 2016 08:29 AM PDT

I have an array of array of Images that all have certain categories in an array called categories_images. Images have a start_at field, which sometimes is nil and other times is has a DateTime in them. I want the ones that have a DateTime that start prior to the current DateTime to appear on my page.

I have written the following code:

def now    categories_images.select { |image| image['start_at'] }  end  

This gives me every image that does not have nil for start_at.

So I asked:

def now    categories_images.select { |image| image['start_at']  < DateTime.now }  end  

Thinking it would give me those same images except for the ones that don't have a start_at date earlier than "Now." Instead it gives me:

undefined method `<' for nil:NilClass  

What am I doing wrong? I get that this is likely ruby 102 stuff, but I'm a fresh-faced kid with dreams who could use some help. Is it saying that DateTime.now is nil so it can't inspect it? If so why, isn't that a legit method to apply to DateTime?

Any help will be appreciated.

IndexError - string not matched with Kaminari gem

Posted: 29 Jul 2016 08:09 AM PDT

After upgrade to rails 5, my ajax pagination(kaminari) doesn't work with polymorphic association.

I'm getting this error:

IndexError - string not matched

It seems to trying access a string variable as a hash.

Well, the exact problem is this line in kaminari gem:

@param_name.to_s.scan(/[\w.]+/)[0..-2].inject(page_params){|h, k| h[k] }[$&] = nil

def params_for(page)    page_params = Rack::Utils.parse_nested_query("#{@param_name}=#{page}")    page_params = @params.deep_merge(page_params)      if !Kaminari.config.params_on_first_page && (page <= 1)      # This converts a hash:      #   from: {other: "params", page: 1}      #     to: {other: "params", page: nil}      #   (when @param_name == "page")      #      #   from: {other: "params", user: {name: "yuki", page: 1}}      #     to: {other: "params", user: {name: "yuki", page: nil}}      #   (when @param_name == "user[page]")      @param_name.to_s.scan(/[\w\.]+/)[0..-2].inject(page_params){|h, k| h[k] }[$&] = nil    end      page_params  end  

Any thoughts on this? I'm really stuck!

Why is the first Rspec View test ran always the slowest?

Posted: 29 Jul 2016 08:08 AM PDT

Below is my Rspec output and as you can see the first test to run is always the slowest. The first time it was line 18, the second time it was line 27. Could the test be doing any sort of caching?

❯ spec spec/views/principals/show.html.haml_spec.rb -p                                                            mbc  Run options:    include {:focus=>true}    exclude {:ignore=>true}    All examples were filtered out; ignoring {:focus=>true}    Randomized with seed 25466  ..    Top 2 slowest examples (3.47 seconds, 94.4% of total time):    /principals/show the MINDEX tab a permitted user has tab and a link to the tab      3.41 seconds ./spec/views/principals/show.html.haml_spec.rb:18    /principals/show the MINDEX tab a not-permitted user does not have tab or a link to the tab      0.05673 seconds ./spec/views/principals/show.html.haml_spec.rb:27    Finished in 3.68 seconds (files took 5.98 seconds to load)  2 examples, 0 failures    Randomized with seed 25466    ❯ rspec spec/views/principals/show.html.haml_spec.rb -p                                                            mbc  Run options:    include {:focus=>true}    exclude {:ignore=>true}    All examples were filtered out; ignoring {:focus=>true}    Randomized with seed 33681  ..    Top 2 slowest examples (3.98 seconds, 94.9% of total time):    /principals/show the MINDEX tab a not-permitted user does not have tab or a link to the tab      3.73 seconds ./spec/views/principals/show.html.haml_spec.rb:27    /principals/show the MINDEX tab a permitted user has tab and a link to the tab      0.25015 seconds ./spec/views/principals/show.html.haml_spec.rb:18    Finished in 4.2 seconds (files took 6.91 seconds to load)  2 examples, 0 failures    Randomized with seed 33681  

And here are my tests....

RSpec.describe "/principals/show" do      before do      @principal = FactoryGirl.build_stubbed(:principal)      FactoryGirl.build_stubbed(:financial_statement, principal: @principal)      @financial_statements = @principal.financial_statements.paginate(per_page: 5, page: 1)      @merchants_index = MerchantsIndex.new(@principal)      allow(@view).to receive(:current_user).and_return(mock_model(User).as_null_object)      allow(@view).to receive(:permitted_to?).and_return(true)    end      #it "works" do    #  expect { render }.not_to raise_error    

No comments:

Post a Comment