I have a belongs_to association, where months belongs_to wallpaper. The Months table has a column called :wallpaper_id which is being used to get the id of the Wallpaper.
months_controller:
#wallpaper = Wallpaper.find(:wallpaper_id => params[:wallpaper_id])
#month = #wallpaper.months.find(params[:id])
But I get an error: Unknown key(s): wallpaper_id
#wallpaper = Wallpaper.find(params[:wallpaper_id])
#month = #wallpaper.months.find(params[:id])
or
#month = Month.where(:wallpaper_id => params[:wallpaper_id], :id => params[:id])
Related
I've got these models in my Rails 6 application:
class Client < ApplicationRecord
belongs_to :account
has_many :people
end
class Person < ApplicationRecord
belongs_to :client
end
class Payment < ApplicationRecord
belongs_to :client
end
In my SharesController I am trying to generate the total payments for each client and show them as a pie chart:
class SharesController < ApplicationController
def index
#clients = current_account.clients.joins(:payments)
.where(:payments => {:date => #range, :currency => #currency})
.order("sum_payments_#{#part} DESC")
.group("clients.id", "clients.name")
.having("sum_payments_#{#part} > 0")
.sum("payments.#{#part}")
end
end
The problem with this is that it groups by client correctly. However, rather than showing each client's name I want to show the last_name of each client's first nested person.
How can this be done?
Thanks for any help.
You should try to create a join between Client and Person and then use uniq to avoid duplicated clients.
You could try something like this (I'm not sure if this code works but just to make it clearer what I mean)
#clients = current_account.clients.joins(:payments, :people)
.where(:payments => {:date => #range, :currency => #currency})
.order("sum_payments_#{#part} DESC")
.group("clients.id", "people.last_name")
.having("sum_payments_#{#part} > 0")
.sum("payments.#{#part}")
I have two Relations (class)
class RecommendedForType < ActiveRecord::Base
attr_accessible :description, :name
has_many :recommended_for_type_restaurants
end
And
class RecommendedForTypeRestaurant < ActiveRecord::Base
attr_accessible :recommended_for_type_id, :restaurant_id, :user_id
belongs_to :restaurant
belongs_to :user
belongs_to :recommended_for_type
def self.get_count(rest_id)
r = RecommendedForTypeRestaurant.where(restaurant_id: rest_id)
#result = r.includes(:recommended_for_type)
.select("recommended_for_type_id, recommended_for_types.name")
.group ("recommended_tor_type_id, recommended_for_types.name")
.count
end
end
if I call
RecommendedForTypeRestaurant.get_count(1) # get stat of restaurant_id: 1
I get
{"dinner"=>1, "fast food"=>1, "lunch"=>3, "romantic dinner"=>1}
My goal is to get both id and name of RecommendTypeFor in the return result as well. currently i can only make it return either id or name. Something like this
{{"id" => 1, "name" => "dinner", "count" => 1}, {"id" =>2, "name" => "lunch", "count" => 3} }
For sure i can do another round of sql once i get id or name to create that hash but i think that not the efficient way. Appreciate any help or suggestion :)
You need to group separately, try the following group.
.group ("recommended_tor_type_id", "recommended_for_types.name").count
I believe that if you remove the .count at the end and change the select to:
.select("count(*), recommended_for_type_id, recommended_for_types.name")
You will get an array of models that will have the attributes you need and the count.
You should be able to test it out in the console by do something like this:
r = RecommendedForTypeRestaurant.where(restaurant_id: rest_id)
#result = r.includes(:recommended_for_type)
.select("recommended_for_type_id, recommended_for_types.name, count(*)")
.group ("recommended_tor_type_id, recommended_for_types.name")
#result.each do |r|
puts r.recommended_for_type_id
puts r.name
puts r.count
end
Hope it helps!
Problem:
In my customer model, I want to sum up all transactions where each payments' status is successful and either the customer_id matches the id of the current instance or the current instance's parent_id. First, I was unable to get this to work at all because I was trying to do it all in one query. Now I have what I'm looking for, but I'm afraid I'm not being nearly as efficient as I could be.
Context:
The transactions table has a customer_id column
the customers table has a parent_id column.
Customer class has_many :transactions
Transactions class belongs_to :customer
Transactions class has_many :payments
Here are my models:
class Customer < ActiveRecord::Base
has_many :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :customer
has_many :payments
end
class Payment < ActiveRecord::Base
has_one :transaction
end
Question:
If this is the model property I'm using currently, how can I improve its performance, if at all?
def total_spent
if customer_type == 1 # "child" customer
Transaction.joins(:payments).where('payments.status' => 3).sum(:amount, :conditions => ['customer_id = ?', id])
elsif customer_type == 2 # "parent" customer
temp_transactions = Transaction.joins(:payments).where('payments.status' => 3)
temp = temp_transactions.sum(:amount, :conditions => ['customer_id = ?', id])
Customer.find_all_by_parent_group_id(id).each do |c|
temp = temp + temp_transactions.sum(:amount, :conditions => ['customer_id = ?', c.id])
end
temp
end
end
Transaction.joins(:payments)
.joins(:customer)
.where(:payments => {:status => 3})
.where("customers.id = ? or customers.parent_id = ?", 5, 5)
.sum(:amount)
SELECT SUM(amount) AS sum_id
FROM "transactions"
INNER JOIN "payments" ON "payments"."transaction_id" = "transactions"."id"
INNER JOIN "customers" ON "customers"."id" = "transactions"."customer_id"
WHERE
"payments"."status" = 3
AND (customers.id = 5 or customers.parent_id = 5)
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.
I've been trying to make this query work for the last couple of hours, but I can't. So I hope someone can help.
Here's the error:
Mysql::Error: Unknown column 'network_id' in 'where clause': SELECT networks.* FROM networks WHERE (network_id = 1,2)
Here are my models:
class Network < ActiveRecord::Base
belongs_to :customer
has_many :user_network_relations
class Customer < ActiveRecord::Base
has_one :network, :dependent=>:destroy
accepts_nested_attributes_for :network
class UserNetworkRelation < ActiveRecord::Base
belongs_to :network
accepts_nested_attributes_for :network
controller
#user = User.find(params[:id])
#user_approved = UserNetworkRelation.find(:all,:conditions => ['user_id = ? and status =? ', #user, "approved"])
#networks = Network.find(:all,:conditions => ['network_id = ?',#user_approved])
#user_networks = Customer.find(#networks)
Any help is appreciated. Thanks in advance!
The error is in this line:
#networks = Network.find(:all,:conditions => ['network_id = ?',#user_approved])
You are explicitly telling ActiveRecord that you want to restrict the column network_id which obviously doesn't exist. Probably you meant the id column. The correct line could read as follows:
#networks = Network.where(:id => #user_approved).all
or equivalently
#networks = Network.where('id = ?', #user_approved).all
Note that in my example, I used the new ActiveModel / AREL syntax of Rails 3. You used the deprecated (but still supported) Syntax of Rails 2. You should switch to the new syntax as it allows you to chain queries which is mightier and much more readable. See the documentation on how to use the new AREL syntax.