Combine Scope with current_user - ruby-on-rails

i have a scope like this :
class InventoryItem < ActiveRecord::Base
belongs_to :inventory
belongs_to :game_item
# define custom scopes to get equipped inventory items for user
scope :equipped, where(:is_equipped => 1)
scope :item, lambda { |item_type|
joins(:game_item).
includes(:game_item).
where("game_items.item_type = ?", item_type ).
limit(1)
}
can i get the current_user model that also includes equipped items in one command ? (with includes maybe ?)

Assuming that your inventory belongs to a user, you could include the current_user model using this:
scope :equipped, where(:is_equipped => 1).includes(:inventory => :user)
This tells Rails to include the inventory model and the associated user model for that inventory. If you wanted to do the same for the item scope you could do this:
scope :item, lambda { |item_type|
includes(:game_item).
includes(:inventory => :user).
where("game_items.item_type = ?", item_type ).
limit(1) }

Related

select specific attributes from array rails

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.

Join scope in Rails 3

I'd like to write a Rails 3 scope, on Client, to do the following:
select * from clients c, dependents d
where d.last_name like '%ss%' and c.id = d.client_id;
Dependent model:
class Dependent < ActiveRecord::Base
belongs_to :client
scope :by_last_name, (lambda do |name| { :conditions => ['last_name LIKE ?', "#{name}%"]} end )
Client model:
class Client < ActiveRecord::Base
has_many :dependents, :dependent => :destroy
I have not yet been able to get a scope join to work syntactically. The dependent's last name needs to be passed in as a parameter.
Thanks.
Try this:
class Client < ActiveRecord::Base
scope :by_last_name, lambda { |last_name| includes(:dependents).where("dependents.last_name LIKE ?", "#{last_name}%") }
then call
Client.by_last_name "last_name"
Edit: Changed the code to reflect your problem.
Also find_by_id(1) is the same as find(1) except that it does not throw an error when nothing is found, instead it returns nil.
Try the following:
scope :by_last_name, lambda {|name| where("dependents.last_name like ?", "'%#{name}%'")

Is it possible to assign multiple has_many ":as" polymorphic relation on same field?

Having my db setup like this ("type" is always User although I have different kind of User via STI):
class User
# fields
# :id
# :sender_id, :sender_type
# :recipient_id, :recipient_type
end
Postcard model:
class Postcard < ActiveRecord::Base
belongs_to :owner, :class_name => User
belongs_to :recipient, :class_name => User
end
I'd like to setup the User model something like this:
class User < ActiveRecord::Base
has_many :postcards, :as => [:sender or :recipient] # this is not working
end
So I could say:
user.postcards
Is it possible?
PS: I've also tried this road:
has_many :postcards, :finder_sql => Proc.new { "SELECT * FROM postcards WHERE postcards.owner_id=#{id} OR postcards.recipient_id=#{id}" }
But found myself stuck on scopes as :finder_sql recreates a whole new SQL:
User.postcards.by_status('new').size
As mentioned by joelparkerhenderson I need to think differently my association strategy.
As I'd like to have:
user.postcards
My answer is simply to use scopes in Postcard model:
scope :of_user, lambda { |user| where("recipient_id = ? OR owner_id = ?", user.id, user.id) }
So I can invoke:
Postcard.of_user user
I could even wrap it in User model:
def postcards
Postcard.of_user self
end

Rails 3 joining a related model with it's default scope

I'm trying to query across models with the following setup
Class Scorecard < AR::Base
default_scope where(:archived => false)
belongs_to :user
has_many :scorecard_metrics
end
Class ScorecardMetric < AR::Base
belongs_to :scorecard
end
Class User < AR::Base
has_many :scorecards
end
I am trying to query from scorecard metrics with a named scope that joins scorecard and I want it to include the default scope for scorecard, my current implementation (which works) looks like this
# on ScorecardMetric
scope :for_user, lambda {
|user| joins(:scorecard).
where("scorecards.user_id = ? and scorecards.archived = ?", user.id, false)
}
This just seems messy to me, is there any way to join and include the default scope of the joined association?
Looks like I found the answer I was looking for, I just did this
scope :for_user, lambda { |user| joins(:scorecard).where('scorecards.user_id = ?', user.id) & Scorecard.scoped }
which is much nicer without the duplicated logic

How do I write a named_scope for one resource through another?

I have a groups resource that belongs_to Workouts. Workouts can be public or private and are designated as such by the column share in the workout table (which is an integer and contains a 1 if the workout is public).
I am trying call all groups that are associated with public workouts. I assume this needs to be done through a named_scope but I am unsure of the syntax.
In the groups_controller I am assuming I would call:
#groups = Group.public_groups.all
How should I write the named_scope in Group.rb? (I'm in rails 2.3.8)
named_scope :public_groups, ...
Here's one way to do it:
class Group < ActiveRecord::Base
belongs_to :workout
named_scope :public, {:conditions => 'workouts.share = 1', :include => :workout}
end
#groups = Group.public.all

Resources