Rails: Named scope works on Class but not instance of Class - ruby-on-rails

Given the following code:
user_decorator.rb
Refinery::User.class_eval do
has_many :employees, :class_name => 'Refinery::Employee'
scope :active_employees,
lambda {
joins(:employees).merge(::Refinery::Employee.active)
}
end
employee.rb
module Refinery
class Employee < ActiveRecord::Base
belongs_to :user, :class_name => 'Refinery::User'
scope :active, where(:retired => false)
end
end
running rails console...
> ::Refinery::User.active_employees
=> [ .......... lots of records etc ]
> user = ::Refinery::User.where(:username => 'test').first
=> #<Refinery::User .... etc etc>
> user.active_employees
NoMethodError: undefined method `active_employees' for #<Refinery::User:0x000000051330f8>
What am I doing wrong?

A scope is related to the model, and not to an instance of that model.
If you want to do that, you have to create a method that does the same.
At least, I think so...

Related

Rails Active query return most associated products and then the rest without associations - will pagination

I'm hoping this would return ALL products beginning with those with the most associations (some products don't have associations):
#products = Product.search(params[:search]).paginate(:per_page => 10, :page => params[:page]).most_popular
My models:
class Product < ActiveRecord::Base
has_many :associations
has_many :users, :through => :associations
scope :most_popular, -> { select("products.*, count(associations.product_id) AS count_popular").joins(:associations).group("products.id").order("count_popular DESC") | Product.all.order("id DESC")}
class Association < ActiveRecord::Base
belongs_to :user
belongs_to :product
attr_accessible :product_id
end
This seems to work when I list everything at once, but I get the error when also using will_pagination pagination:
NoMethodError - undefined method `total_pages' for #<Array:0x007fa5c5baef60>:
I solved the problem by doing this
require 'will_paginate/array'
#products = Product.search(params[:search]).most_popular.paginate(:per_page => 10, :page => params[:page])
Apparently will paginate is not good with arrays unless you tell it to.

Using ActiveRelation with :joins on polymorphic has_one to implicitly create relation

We can use ActiveRelation like this:
MyModel.where(:field => "test").create => #<Message ... field:"test">
But it doesnt work for joins with polymorphic has_one associations:
class RelatedModel < AR::Base
# has :some_field
belongs_to :subject, :polymorphic => true
end
class MyModel < AR::Base
# need some dirty magic here
# to build default related_model with params from active_relation
has_one :related_model, :as => :subject, :dependent => :destroy
end
describe MyModel do
it "should auto-create has_one association with joins" do
test = MyModel.joins(:related_model).where("related_models.subject_type" => "MyModel", "related_models.some_field" => "chachacha").create
test.related_model.should_not be_nil
test.related_model.some_field.should == "chachacha"
test.related_model.subject_type.should == "MyModel"
test.related_model.subject_id.should == test.id
# fails =)
end
end
Is it possible to extract active_relation params, pass them to MyModel for use in before_create and build RelatedModel with them?
Diving into ActiveRecord sources i found that
ActiveRecord::Relation covers 'create' with 'scoping' method.
ActiveRecord::Persistance 'create' calls 'initialize' from ActiveRecord::Core.
ActiveRecord::Core 'initialize' calls 'populate_with_current_scope_attributes'
This method declared in ActiveRecord::Scoping uses 'scope_attributes' declared in ActiveRecord::Scoping::Named.
scope_attributes creating relation 'all' and calls 'scope_for_create' on it.
'ActiveRecord::Relation's 'scope_for_create' uses only 'where_values_hash' from current_scope that does not contain rules like 'related_models.subject_type' (this values are contained in where_clauses). So we need to have simple key-value wheres to be used with 'create' on ActiveRecord::Relation. But ActiveRecord not clever enough to know that 'some_field' in where clause should be used with join table.
I found it can be implemented only by accessing where options with self.class.current_scope.where_clauses in 'before_create' on MyModel, parsing them and setting up attributes.
class MyModel < AR::Base
before_create :create_default_node
def create_default_node
clause = self.class.current_scope.where_clauses.detect{|clause| clause =~ /\`related_models\`.\`some_field\`/}
value = clause.scan(/\=.+\`([[:word:]]+)\`/).flatten.first
self.create_node(:some_field => value)
end
end
But it is so dirty, then i decided to find simpler solution and inverted dependency as described in Railscast Pro #394, moved RelatedModel functionality to MyModel with STI. Actually i needed such complicated relation creation because RelatedModel had some functionality common for all models (acts as tree). I decided to delegate 'ancestors' and 'children' to RelatedModel. Inverting dependency solved this problem.
class MyModel < AR::Base
acts_as_tree
belongs_to :subject, :polymorphic => true
end
class MyModel2 < MyModel
end
class RelatedModel < AR::Base
# has :some_field
has_one :my_model, :as => :subject, :dependent => :destroy
end
MyModel.create{|m| m.subject = RelatedModel.create(:some_field => "chachacha")}
MyModel.ancestors # no need to proxy relations

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.

Rails has_many :through and Setting Property on Join model

Similar to this question, how do I set a property on the join model just before save in this context?
class Post < ActiveRecord::Base
has_many :post_assets
has_many :assets, :through => :post_assets
has_many :featured_images, :through => :post_assets, :class_name => "Asset", :source => :asset, :conditions => ['post_assets.context = ?', "featured"]
end
class PostAssets < ActiveRecord::Base
belongs_to :post
belongs_to :asset
# context is so we know the scope or role
# the join plays
validates_presences_of :context
end
class Asset < ActiveRecord::Base
has_many :post_assets
has_many :posts, :through => :post_assets
end
I just want to be able to do this:
#post = Post.create!(:title => "A Post")
#post.featured_images << Asset.create!(:title => "An Asset")
# ...
#post = Post.first
#featured = #post.featured_images.first
#=> #<Asset id: 1, title: "An Asset">
#featured.current_post_asset #=> #<PostAsset id: 1, context: "featured">
How would that work? I've been banging my head over it all day :).
What currently happens is when I do this:
#post.featured_images << Asset.create!(:title => "An Asset")
Then the join model PostAsset that gets created never gets a chance to set context. How do I set that context property? It looks like this:
PostAsset.first #=> #<PostAsset id: 1, context: nil>
Update:
I have created a test gem to try to isolate the problem. Is there an easier way to do this?!
This ActsAsJoinable::Core class makes it so you can have many to many relationships with a context between them in the join model. And it adds helper methods. The basic tests show basically what I'm trying to do. Any better ideas on how to do this properly?
Look at the has_many options in the ActiveRecord::Associations::ClassMethods API located here: http://rails.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001316
This is the most interesting quote:
:conditions
Specify the conditions that the associated object must meet in order to be included as a WHERE SQL fragment, such as authorized = 1. Record creations from the association are scoped if a hash is used. has_many :posts, :conditions => {:published => true} will create published posts with #blog.posts.create or #blog.posts.build.
So I believe your conditions must be specified as a hash, like so:
class Post < ActiveRecord::Base
has_many :post_assets
has_many :featured_post_assets, :conditions => { :context => 'featured' }
has_many :assets, :through => :post_assets
has_many :featured_images, :through => :featured_post_assets,
:class_name => "Asset", :source => :asset,
end
And you should also do the following:
#post.featured_images.build(:title => "An asset")
instead of:
#post.featured_images << Asset.create!(:title => "An Asset")
This should call the scoped asset build, as suggested in the quote above to add the context field to asset. It will also save both the join model object (post_asset) and the asset object to the database at the same time in one atomic transaction.

has_many through and saving to join table

I have the following:
class Invite < ActiveRecord::Base
belongs_to :user
has_many :invite_recipients
has_many :recipients, :through => :invite_recipients
end
class InviteRecipient < ActiveRecord::Base
belongs_to :invite
belongs_to :user_comm
validates_associated :user_comm, :invite
validates_uniqueness_of :user_comm_id, :scope => :invite_id
end
class UserComm < ActiveRecord::Base
end
I'd like to create a method for Invite with invite_text and a list of UserComms as the variables and then have it create a new invite with the following validations:
1. All UserComms are unique
2. The invite isn't saved unless all the associated InviteRecipients are saved as well
(in other words, the invite isn't valid unless all the created InviteRecipients are valid)
I'm not familiar with how to create model functions. Moreover, when I try something like this:
i = Invite.new(:invite_text => 'come join')
ir1 = InviteRecipient.new(:invite => i, :user_comm => user_comm1)
ir2 = InviteRecipient.new(:invite => i, :user_comm => user_comm2)
i.invite_recipients = [uc1, uc2]
i.save!
I get: SystemStackError: stack level too deep
You need use i.recipients not invite_recipients!
Like this:
i.recipients.create(:user_comm => user_comm1)
i.recipients.create(:user_comm => user_comm2)

Resources