I'm building an application that has a bunch of Monthly Total reports. Most of them are very similar and they are all working now but the code sucks. I have to clean this up and trying to figure out the best approach in doing so.
def active_monthly_total_by_type
respond_to do |format|
format.html
format.json {
#results = #current_account.items.totals_by_month(params[:selected_year], :status_change_date).with_type.active
render :json => #results.collect{ |result| { :type => result.type, :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
end
end
def active_monthly_total
respond_to do |format|
format.html
format.json {
#results = #current_account.items.totals_by_month(params[:selected_year], :status_change_date).active
render :json => #results.collect{ |result| { :jan => result.jan, :feb => result.feb, :mar => result.mar, :apr => result.apr, :may => result.may, :jun => result.jun, :jul => result.jul, :aug => result.aug, :sep => result.sep, :oct => result.oct, :nov => result.nov, :dec => result.dec } }
}
I have 6 total methods like this and I'm trying to figure out if I pass it a param of active or inactive
params[:active]
if I can attach it to this call
#results = #current_account.items.totals_by_month(params[:selected_year], :status_change_date).params[:active]
if anyone can help or give me some advise where I can look for information I would love to have one method that controls all of these calls since they are the same. Here is the model scope:
def self.totals_by_month(year, date_type)
start_date = year.blank? ? Date.today.beginning_of_year : Date.parse("#{year}0101").beginning_of_year
end_date = year.blank? ? Date.today.end_of_year : Date.parse("#{year}0101").end_of_year
composed_scope = self.scoped
start_date.month.upto(end_date.month) do |month|
composed_scope = composed_scope.select("COUNT(CASE WHEN items.#{date_type.to_s} BETWEEN '#{start_date.beginning_of_month}' AND '#{start_date.end_of_month}' THEN 1 END) AS #{Date::ABBR_MONTHNAMES[month].downcase}")
start_date = start_date.next_month
end
composed_scope
end
I found a unique way to do this. I created a method called pie_chart and bar_chart which handles HTML and JSON for the requests and implemented this structure
/reports/:method/:year/:name/
send(params[:method],#current_account.items.send(params[:scope], params[:year]))
Where the URL would be /reports/pie_chart/2010/count_types_by_year
I have a pie_chart method in my controller and a count_types_by_year as the scope in my model and works like a charm Completely makes it dynamic and also makes it flexible for new additions...DRY baby DRY
Related
class CartItemsController < ApplicationController
before_filter :initialize_cart, :check_not_signedin
def create
product = Product.find(params[:product_id])
kart = initialize_cart
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
if qty == 0
#item = CartItem.new(:cart_id => kart.id, :product_id => product.id, :quantity => qty+1)
if #item.save
flash[:success] = "Product added"
redirect_to category_products_path
end
else
if CartItem.where("cart_id = ? AND product_id = ?", kart.id, product.id).first.update_column(:quantity, qty+1)
flash[:success] = "Product updated"
redirect_to category_products_path
end
end
end
When I am trying to run this I'm getting the following error
"Can't convert FixNum into Array"
app/controllers/cart_items_controller.rb:17:in `create'
Please help!
The following line should return a ActiveRecord::Relation into qty:
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
You should use qty.count instead: qty.count == 0
Also, you can't add a ActiveRecord::Relation with 1 like this: qty+1. It will give you the error message you had.
I'm not sure what you are trying to do, but I suggest you use the debugger gem to help you troubleshoot your problem. Follow the guide here to setup, it's very simple to setup: http://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debugger-gem
Then, place debugger in your code:
product = Product.find(params[:product_id])
kart = initialize_cart
qty = CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
debugger # <---- here
if qty == 0
#item = CartItem.new(:cart_id => kart.id, :product_id => product.id, :quantity => qty+1)
if #item.save
Then you can find out more while you stopped at the debugger breakpoint, you can do stuff like:
qty.class
qty.count
# etc
Also, you can run rails console for testing.
I'm guessing that the following line is returning an Array:
CartItem.select(:quantity).where(:cart_id => kart.id, :product_id => product.id)
If this is the case then you can't simply add +1 to it on this line:
if CartItem.where("cart_id = ? AND product_id = ?", kart.id, product.id).first.update_column(:quantity, qty+1)
If this is not the case, can you point out which line is number 17 as pointed out in the error message.
I'm trying to develop some tests for a method which is responsible for retrieve some users created after some date. I don't know how to mock tests for it. The method is the following:
def user_list
render :nothing => true, :status => 422 if params[:time_param].blank?
time = Time.parse(params[:time_param])
#users = User.find(:all, :select => 'id, login, email',
:conditions => ["created_at > ?", time])
render :json => { :users => #users }
end
end
This is my spec:
describe UsersController do
context "when receiving time parameter" do
before (:each) do
#time_param = "2013-01-25 00:01:00"
user1 = mock_model(User, :created_at => Time.parse('2013-01-25 00:00:00'))
user2 = mock_model(User, :created_at => Time.parse('2013-01-25 00:01:00'))
user3 = mock_model(User, :created_at => Time.parse('2013-01-25 00:02:00'))
#users = []
#users << user1 << user2 << user3
end
it "should retrieve crimes after 00:01:00 time" do
User.stub(:find).with(:all, :select => 'id, login, email').and_return(#users)
get :user_list, { :time_param => #time_param }
JSON.parse(response.body)["users"].size.should eq 1
end
end
end
The problem is that it always returns all users despite of returning just one. (the last one). Where am I mistaking?
Help me =)
You are not testing what you have to test there, on a controller spec you only need to test that the method that you want is called with the parameters that you want, in your case, you have to test that the User model receives :find with parameters :all, :select => 'id, login, email', :conditions => ["created_at > ?", time] (with time the value that should be there.
Also, that logic does not belong to the controller, you should have a class method on User, something like select_for_json(date) to wrap around that find method (you can find a better name for it)
Then your controller becomes:
def user_list
render :nothing => true, :status => 422 if params[:time_param].blank?
time = Time.parse(params[:time_param])
#users = User.select_for_json(time)
render :json => { :users => #users }
end
your spec would be
before(:each) do
#users = mock(:users)
#time_param = "2013-01-25 00:01:00"
end
it "retrieve users for json" do
User.should_receive(:select_for_json).once.with(#time).and_return(#users)
get :user_list, { :time_param => #time }
assigns(:users).should == #users
end
that way you are sure that your action does what it does and the spec is A LOT faster since you are not creating users
then you can test that method on the model specs, there you have to create some users, invoke that method and check the users returned (don't stub/mock anything on your model spec)
Your stub call is telling find to ignore what it thought it was supposed to do and return #users instead. It will not attempt to match the conditions.
Unfortunately, to do your test I think you're going to have to allow the find to execute through your database which means you can't use mock_models. You probably will want to do either User.create(...) or FactoryGirl.create(:user) (or some other factory / fixture).
Of course doing it this way, you may hit MassAssignment issues if you use attr_accessible or attr_protected, but those are easy enough to stub out.
I hope that helps.
In my view, I've got a fiddly loop which creates 500 SQL queries (to get the info for 500 books). How can I avoid lots of SQL queries by loading a variable up in the controller?
My current (pseudo) code:
controller index action:
#books = Book.scoped.where(:client_id => #client.id).text_search(params[:query])
#feature_root = Book.multiple_summary_details_by_category( #books )
#...returns a hash of books
#features = #feature_root.to_a.paginate(:page => params[:page], :per_page => 4)
index.html.haml
= render :partial => "feature", :locals => { :features => #features }
_features.html.haml
- features.each_with_index do |(cat_name, array_of_books), i|
%h2
= cat_name
- array_of_books[0..10].each do |feature|
= link_to image_tag(feature[:cover], :class => "product_image_tiny"), book_path(feature[:book])
# more code
- array_of_books.sort_by{ |k, v| k["Author"] }.each do |feature|
- feature.each do |heading,value|
%span.summary_title
= heading + ':'
%span.summary_value
= value
What have you tried so far? It should be quite easy with standard ActiveRecord queries as documented in http://guides.rubyonrails.org/active_record_querying.html.
Also, instead of
array_of_books.sort_by{ |k, v| k["Author"] }
try something like
Book.order("author DESC")
(not sure about your exact model here) to let the db do the sorting rather than putting them in an array and let ruby handle it.
In model:
def self.get_by_slug(slug)
self.where("slug = ?", slug)
end
In controller:
#route: match '/category/:slug', :to => 'category#index', :as => "category_jobs"
#category = Category.get_by_slug(params[:slug])
#jobs = Job.where("category_id = ? AND expires_at > ?", #category.id, DateTime.now)
.paginate(:page => params[:page], :per_page => Jobeet::Application::MAX_JOBS_ON_CATEGORY_PAGE)
.order("expires_at desc")
When I trying get category.id in controller I am getting error:
undefined method `id' for #
Could somebody give me any advice?
If you expect a single record you should do:
#category = Category.get_by_slug(params[:slug]).first
because .where(something) doesn't return a single record.
class ArticlesController < ApplicationController
def index
#articles = Article.by_popularity
if params[:category] == 'popular'
#articles = #articles.by_popularity
end
if params[:category] == 'recent'
#articles = #articles.by_recent
end
if params[:category] == 'local'
index_by_local and return
end
if params[:genre]
index_by_genre and return
end
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #articles }
end
end
def index_by_local
# 10 lines of code here
render :template => 'articles/index_by_local'
end
def index_by_genre
# ANOTHER 10 lines of code here
render :template => 'articles/index_by_genre'
end
end
As you can see from above. My controller is not exactly thin. What its doing is, depending on the params that were passed, it interacts with the model to filter out records.
And if params[:local] or params[:genre] was passed. Then it calls its own methods respectively (def index_by_local and def index_by_genre) to do further processing. These methods also load their own template, instead of index.html.erb.
Is this quite typical for a controller to look? Or should I be refactoring this somehow?
We can move the first few lines into the model(article.rb):
def get_by_category(category)
# Return articles based on the category.
end
In this way we can completely test the article fetching logic using unit tests.
In general move all the code related to fetching records inside model.
Controllers in general
should authorize the user
get records using the params and assign them to instance variables
[These must typically be function
calls to model]
Render or redirect
I would define scopes for each of the collections you want to use.
class Article < ActiveRecord::Base
...
scope :popular, where("articles.popular = ?", true) # or whatever you need
scope :recent, where(...)
scope :by_genre, where(...)
scope :local, where(...)
...
def self.filtered(filter)
case filter
when 'popular'
Article.popular, 'articles/index'
when 'recent'
Article.recent, 'articles/index'
when 'genre'
Article.by_genre, 'articles/index_by_genre'
when 'local'
Article.local, 'articles/index_by_local'
else
raise "Unknown Filter"
end
end
end
Then in your controller action, something like this:
def index
#articles, template = Article.filtered(params[:category] || params[:genre])
respond_to do |format|
format.html { render :template => template }
format.xml { render :xml => #articles }
end
end