Counter cache doesn't get updated - not sure why - ruby-on-rails-3

I have a stores application on github. I'm trying to implement counter_cache for two models, 1. Divisions model and 2. Products model. For some reason I'm not sure of the counter cache(divisions_count) doesn't get incremented automatically for the Company model whenever I create a new Division and similarly the products_count doesn't get incremented for the Divisions model when I add a new product to the division.
I'm on rails 3.2.11 and on ruby 1.9.3-p327
My application is only at POC level.
PFB the model structure wrt Company, Division and Product:-
company.rb
class Company < ActiveRecord::Base
attr_accessible :contact_no, :email_id, :fax_no, :name, :website, :divisions_count
has_many :divisions #just added divisions_count to attr_accessible not sure if it helps
has_many :products, :through => :divisions
end
division.rb
class Division < ActiveRecord::Base
attr_accessible :company_id, :name, :products_count
#just added products_count to attr_accessible not sure if it helps
belongs_to :companies, :counter_cache => true
has_many :products
end
product.rb
class Product < ActiveRecord::Base
attr_accessible :division_id, :model, :name, :price
belongs_to :divisions, :counter_cache => true
end
In case you want to refer to the migrations that I've created for the counter cache implementation , you may find them here.

I believe the problem is that you’ve set up belongs_to incorrectly by using the plural name. Switching to singular solves the problem, i.e.
# pseudo diff:
- belongs_to :companies, :counter_cache => true
+ belongs_to :company, :counter_cache => true
- belongs_to :divisions, :counter_cache => true
+ belongs_to :division, :counter_cache => true
When editing models/associations I found it helpful to think of an actual instance. So, it makes sense that the “Windows”-division belongs to “Microsoft”-company, but it makes no sense that it belongs to “Microsoft”-companies. Or just remember belongs_to is always singular and has_many is always plural.
If you need your divisions to belong to multiple companies, you need to use a different association called “has and belongs to many” or HABTM for short (see [1]).
[1] http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Related

Handling relationship with ActiveRecord

I have two models to make a relationship between them, where I need to access stores of a radar and the radars of a store. A radar could monitoring zero or many stores. A store could belong to zero, one or many radars.
I would like to have something like this:
store = Store.first
store.radars #all radars of the store location
And the opposite too:
radar = Radar.first
radar.stores #all stores of the radar location
My classes:
class Store < ActiveRecord::Base
attr_accessible :title, :description, :user, :store_group, :city,
:neighborhood, :sublocality, :post_code, :route,
:street_number, :latitude, :longitude
end
class Radar < ActiveRecord::Base
attr_accessible :name, :radius, :latitude, :longitude, :user
end
How can I create a migration to handle this?
What you are looking for is a has_and_belongs_to_many association between radars and stores. The question you need to ask your self is will there ever be any attributes on the the joining between the two models? If so you might considering using an explicit join model, that will hold those attributes. In that case you would be looking at a has_many :through association.
see http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association for information on the HABTM association.
your migration for a HABTM would be something like this.
class CreateRadarStores < ActiveRecord::Migration
create_table :radars_stores, :id => false do |t|
t.belongs_to :radar
t.belongs_to :store
end
end
The order of the table name is important, since by default rails creates it in alphabetical order of the models.
Your models would need to be updated to include the HABTM
class Store < ActiveRecord::Base
has_and_belongs_to_many :radars
....
end
class Radar < ActiveRecord::Base
has_and_belongs_to_many :stores
....
end
or if using a has many :through look here http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
Building that join model would be up to you depending upon attributes reuqired.

rails model doubts has_one, has_many, belongs_to

I have created 3 models for a small system. The intent here is to handle users, companies and their relationships. I anticipate to do a lot of lookups over the intersections and also want to have strict controls over the joins available, in that a user can only belong to one company, but company can have many users. I feel the best way to represent this is with the below. I would like some feedback on this preposition. So far my tests have worked fine validating my thesis and some small implementation efforts have gone fine, but when I look through a list of users to find their company I somehow run into issues and I have a feeling it is related to the has_one relationship, but not sure. Again thanks for constructive feedback.
class User < ActiveRecord::Base
has_one :companyrelationship, foreign_key: "user_id"
has_one :company, :through => :companyrelationship, dependent: :destroy
class Company < ActiveRecord::Base
has_many :companyrelationships
has_many :users, :through => :companyrelationships
class CompanyRelationship < ActiveRecord::Base
belongs_to :company
belongs_to :user
validates :user_id, presence: true, uniqueness: true
validates :company_id, presence: true
I do see one thing that I'm pretty sure is an error and won't work. I can also try to add a couple points of constructive criticism.
The error is that the CamelCase model name is converted to underscorey (sorry, I can't remember the term for that right now) case. All your references to companyrelationship should add an underscore. You can override the convention by setting the :class_name attribute, but I don't think that's what you wanted.
Another issue I see which isn't technically wrong, but is almost certainly not what you want is that the dependent: :destroy would delete the Company when you deleted a User. (Actually, I'm not sure dependent: :destroy works in a through: relationship.) I assume what you wanted was just to delete the CompanyRelationship. You can read the section on Dependent associations at this link:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
Next point is that the default foreign_key is the model + _id so you don't need to specify it in this case.
My last point is purely a style preference. I like doing my validations by validation type. You're doing them by variable. They are functionally equivalent, so feel to take it with a grain of salt. (I'm pretty sure user and user_id are equivalent, but feel free to stick to user_id if you're more comfortable with it.)
If it were completely up to me, I would code it this way:
class User < ActiveRecord::Base
has_one :company_relationship, dependent: :destroy
has_one :company, through: :company_relationship
class Company < ActiveRecord::Base
has_many :company_relationships
has_many :users, through: :company_relationships
class CompanyRelationship < ActiveRecord::Base
belongs_to :company
belongs_to :user
validates_presence_of :user, :company
validates_uniqueness_of :user
I hope that helps you get further.

Implementing a has_many :through

I am thinking of creating the following models using 'has_many :through':
class Contract < AR::Base
has_many :clientlines
has_many :codelines
has_many :clients, :through => :clientlines
has_many :codes, :through => :codelines
end
class clientlines < AR::Base
belongs_to :contract
belongs_to :client
end
class Client < AR::Base
has_many :clientlines
has_many :contracts, :through => :clientlines
end
class codeline < AR::Base
belongs_to :contract
belongs_to :code
units_alloc -------**I would like to add this attribute after this intermediate
end has been created?
class Code < AR::Base
has_many :codelines
has_many :contracts, :through => :codelines
end
Do I first create the models with 'rails generate model Contract authnum:string, client_id:integer, st_date:date, end_date:date' for example.
Then fill in all of the associations before the migrations?.
Also, my understanding is that all of the join tables are created automatically by rails when using the has_many :through association. When does that happen?
Lastly, as indicated by the **, can I have this attribute in codelines, and do I create a 'rails generate migration add_units_alloc_to_codelines units_alloc:number' in order to add this attribute to the join table? I was also wondering how I declare the number to be too two decimal places?
If you have the time and inclination could you please comment on my proposed design for my database?
Thanks.
by using has_many :through you use a third model that makes the connection between the other two, so rails doesn't automatically build that model, you build it yourself and reference the foreign keys for the other two models.
don't name your models at their plural, always singular. if you can't name them at singular, you're doing it wrong
The order in which you create your models shouldn't matter too much (rails generates some migrations which you can easily modify later)
That units_alloc attribute, just add it to the model when you create it, simple as that!
for 2 decimals use something like t.decimal :amount, :precision => 6, :scale => 2 in your migration (that example gives you 6 digits and 2 decimals)
Read the Rails Guides, it will really help you get out a lot of trouble

Rails basic association

I'm trying to do a basic model association in rails.
Basically I have a List table which stores item_id and user_id.
One user can create multiple "list-items."
Is this the correct way to do it?
Thanks.
class Item < ActiveRecord::Base
has_many :users, :through => :lists
end
class User < ActiveRecord::Base
has_many :items, :through => :lists
end
class List < ActiveRecord::Base
belongs_to :user
belongs_to :item
end
Depending on what you want to reach, your solution is the right one (or not). I see the following cases:
You want to create an n:m association between items and users. So each item could be referenced by many users, and each user references many items. If this is the right context, then your solution is the right one. See the Rails Guides: Associations for more information on that.
An alternative for that situation could be to use the has_and_belongs_to_many Association. The situation is the same, but it does not make sense to talk about lists, there will be no model object for it.
If each users may have many lists, and each list may have many items, your solution would be wrong. This would be no n:m association with list as the join table in between, but two 1:n relations.
The code for the third example would look like that:
class User < ActiveRecord::Base
has_many :items, :through => :lists
has_many :lists
end
class List < ActiveRecord::Base
has_many :items
belongs_to :user
end
class Item < ActiveRecord::Base
belongs_to :list
end
In the first solution, you should add the relations for users to lists and items to list:
class Item < ActiveRecord::Base
has_many :lists
has_many :users, :through => :lists
end
class User < ActiveRecord::Base
has_many :lists
has_many :items, :through => :lists
end
If the "list" entity truly is a pure association/join, that is, it has no inherent attributes of its own, then you can simplify a bit and use has_and_belongs_to_many. Then you don't need a "List" class.
class Item < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :items
end
Rails will look for the references in a "items_users" table, so in your migration, you need to create it a la:
create_table :items_users, :id => false do |t|
t.references :users, :items
end
Many people will tell you to always use has_many :through, but others (like me) will disagree - use the right tool for job.

has_many :through - complicated model

I have a pretty complicated set of models and I'm trying to figure out how to set it all up so that rails will generate chained queries (though I'm not sure it is possible). So my question ends up being: how do I chain these together OR how do I properly paginate this type of function?
First, the high overview.
It is a "social network" and I have users who can be students or teachers. Students and teachers can both follow each other. Both can also do things on the site that result in activity_items. A students can belong to a teacher. Therefore, if a student is following a teacher, they should also see the activity_items of the students under that teacher.
And that is where it gets complicated. I am trying to figure out how to display an activity feed.
Now the models:
model ActivityItem < ActiveRecord::Base
belongs_to :profile, :polymorphic => :true
attr_accessor :posted_by_user
end
model Following < ActiveRecord::Base
belongs_to :profile, :polymorphic => true
belongs_to :following, :polymorphic => true
end
model Student < ActiveRecord::Base
has_many :following_relationships, :as => :profile, :class_name => "Following"
has_many :follower_relationships, :as => :following, :class_name => "Following"
# getting the actual student/teacher model for each relationship
def following
self.following_relationships.reset
following_relationships.collect(&:following)
end
def activity_feed
all = following
all.inject([]) do |result,profile|
result | profile.activity_items
end
end
end
model Teacher < ActiveRecord::Base
[same as student, really it is in an Extension]
end
So the method I'm most concerned about is activity_feed. Without running the large set of queries every time, I'm not sure how to paginate the data. I have a few more methods that go through each activity_item and set posted_by_user to true or false to let me know if it is an activity_item created by someone they are following directly or indirectly (through the teacher).
How can I modify this so that I'm able to either
(A) get a single (or two or three) queries so that I can do a pagination method on it.
(B) how would I properly cache / paginate a large data set like this?