I have CartItem model that has a belongs_to relation with Product
def CartItem
belongs_to :product, :select => "*, get_product_price_for_shop(#{self.shop_id}) as shop_price"
end
As you can see above I have postgresql function that calculates price for specific shop and I want to use it in select clause of products so I can refer to it like this:
#cart_item.product.shop_price
I'm looking for a way to pass shop_id attribute from CartItem to belongs_to :select key.
A quick thought : did you try a proc ?
def CartItem
belongs_to :product, :select => proc { "*, get_product_price_for_shop(#{self.shop_id}) as shop_price" }
end
Related
My relationships are set up like this:
A Project has_many documents
A Document has_one content_body
ContentBody has_many audits
I need to retrieve the Audits having only a project id in a descending order.
Assuming
class Audit
belongs_to :content_body
end
class ContentBody
belongs_to :document
end
class Document
belongs_to :project
end
Then
#audits = Audit.joins(content_body: { document: :project })
.where(projects: {id: some_id })
.order(created_at: :desc)
Or
#audits = Audit.joins(content_body: :document)
.where(documents: {project_id: some_id })
.order(created_at: :desc)
Should do the trick. As for the order you did not specify what column exactly descending should be based on so I assumed created_at
I have post model
class Post < ActiveRecord::Base
acts_as_voteable
end
and Vote model
class Vote < ActiveRecord::Base
scope :for_voter, lambda { |*args| where(["voter_id = ? AND voter_type = ?", args.first.id, args.first.class.name]) }
scope :for_voteable, lambda { |*args| where(["voteable_id = ? AND voteable_type = ?", args.first.id, args.first.class.name]) }
scope :recent, lambda { |*args| where(["created_at > ?", (args.first || 2.weeks.ago)]) }
scope :descending, order("created_at DESC")
belongs_to :voteable, :counter_cache=>true,:polymorphic => true,:touch=>true
belongs_to :voter, :polymorphic => true
attr_accessible :vote, :voter, :voteable
# Comment out the line below to allow multiple votes per user.
validates_uniqueness_of :voteable_id, :scope => [:voteable_type, :voter_type, :voter_id]
end
when I get the post voters with these method
<% #post.voters_who_voted.each do |voter|%>
<%= voter.name %>
<% end %>
I load my database
how can I select only the user name and user id from these array?
update I changed my code I am using thumbs_up gem I pasted less code first to simplify the question
What do you mean by "load database"? If you want to select only id and name columns, then use #post.users.select([:id, :name]).each ...
Or is it about this problem (according to code that you provided)?
UPD.
voters_who_voted loads all voters and returns array https://github.com/bouchard/thumbs_up/blob/master/lib/acts_as_voteable.rb#L113. You have to add own association to Post model:
has_many :voters, :through => :votes, :source => :voter, :source_type => 'User'
It's just example, perhaps voters will clash with already existing method, if any.
Then use it here instead of voters_who_voted
did you try collect method ??
names = #post.users.collect(&:name)
ids = #post.user.collect(&:id)
If you want it to be related you can make a HASH with it. Id's mapped to the names.
I'm trying to join the results of 'SupplierShippingItem' and 'MtlSystemItem' but I keep getting an error:
Association named 'mtl_system_items' was not found; perhaps you misspelled it?
My association is done like this:
SupplierShippingItem.joins(:mtl_system_items).where('supplier_shipping_items.inventory_item_id = mtl_system_items.inventory_item_id SEGMENT1 ILIKE ? OR DESCRIPTION ILIKE ? ', "%#{params[:term]}%", "%#{params[:term]}%")
SupplierShippingItem
class SupplierShippingItem < ActiveRecord::Base
attr_accessible :inventory_item_id, :received_qty, :shipped_qty, :supplier_shipping_list_id, :supplier_planning_schedule_id, :po_number
belongs_to :mtl_system_item, :foreign_key => :inventory_item_id
end
*MtlSystemItem *
class MtlSystemItem < ActiveRecord::Base
attr_accessible :inventory_item_id, :segment1, :description, :primary_uom_code, :inventory_item_status_code, :item_type
has_many :supplier_shipping_items, :foreign_key => :inventory_item_id
end
What I'm trying to achieve is to fetch the items in MtlSystemItem but only if they are found in SupplierShippingItem. I have thousands of items in MtlSystemItem so I want to filter them out a bit. I'll also include a date restriction later on, but I'm blocked by the error.
as the error says, the association is not found. You used mtl_system_items instead of mtl_system_item (singular) which is the association you declared.
Remember that for joins and includes, you need to use the association name. For where, use the table name
SupplierShippingItem.joins(:mtl_system_item)
.where('supplier_shipping_items.inventory_item_id = mtl_system_items.inventory_item_id SEGMENT1 ILIKE ? OR DESCRIPTION ILIKE ? ', "%#{params[:term]}%", "%#{params[:term]}%")
SupplierShippingItem.joins(:mtl_system_items)
should be
SupplierShippingItem.joins(:mtl_system_item)
on your example above:
class SupplierShippingItem < ActiveRecord::Base
belongs_to :mtl_system_item
end
class MtlSystemItem < ActiveRecord::Base
has_many :supplier_shipping_items
end
you can try this ActiveRecord joins:
SupplierShippingItem.find(:all, :joins => :mtl_system_item])
and you can add conditions for this query like this:
SupplierShippingItem.find(:all, :joins => :mtl_system_item, :conditions => ["supplier_shipping_items.id = ?", 1]])
my model is
class Job < ActiveRecord::Base
belongs_to :client
end
class Client < ActiveRecord::Base
has_many :jobs
end
in controller i want get client with sorted jobs.
If i do (without ordering)
#client = Client.find(params[:id], :include => {:jobs => :status})
It is all ok. But if i add ordering:
#client = Client.find(params[:id], :include => {:jobs => :status}, :order => 'job.level DESC')
// :order is dynamicly set (not in this example) - i know about :order in has_many.
the result is only 3 rows (for every job.level one). I logged the sql query and executed it and result is ok, but in app i have only these 3 rows.
What is the right way to sort jobs? Thank you
You could try specifying the order directly in the model instead of the controller
class Job < ActiveRecord::Base
belongs_to :client, :order => 'level DESC'
end
OR
class Client < ActiveRecord::Base
has_many :jobs, :order => 'level DESC'
end
Also, what data type is the level in the Jobs model? If you could post your logs for the sql queries that would be helpful as well. Also, have you tried
:order => 'jobs.level'
instead of the singular job.level used in the code you posted?
This is not what i originally wanted, but it works, so this is answer
#jobs = #client.jobs.find(:all, :order => sort_column + " " + sort_direction)
I was wondering if it was possible to use the find method to order the results based on a class's has_many relationship with another class. e.g.
# has the columns id, name
class Dog < ActiveRecord::Base
has_many :dog_tags
end
# has the columns id, color, dog_id
class DogTags < ActiveRecord::Base
belongs_to :dog
end
and I would like to do something like this:
#result = DogTag.find(:all, :order => dog.name)
thank you.
In Rails 4 it should be done this way:
#result = DogTag.joins(:dog).order('dogs.name')
or with scope:
class DogTags < ActiveRecord::Base
belongs_to :dog
scope :ordered_by_dog_name, -> { joins(:dog).order('dogs.name') }
end
#result = DogTags.ordered_by_dog_name
The second is easier to mock in tests as controller doesn't have to know about model details.
You need to join the related table to the request.
#result = DogTag.find(:all, :joins => :dog, :order => 'dogs.name')
Note that dogs is plural in the :order statement.