Ravindra
Ravindra

Reputation: 1049

how to access data with has_many :through relation

Hi I have three models: company, plan and subscription with following association

    class Company < ActiveRecord::Base
      has_one :plan, :through => :subscriptions
      has_many :subscriptions
    end

    class Subscription < ActiveRecord::Base
      belongs_to :plan
      belongs_to :company
    end

   class Plan < ActiveRecord::Base
      has_many :subscriptions
      has_many :companies, :through => :subscriptions
    end

I have two plans in my application plan 'A' and plan 'B'. Plan 'A' is free and 'B' has some fee. Now i want to get companies registered with plan 'A' and companies with plan 'B'.
I want this data in my model, i know their is definitely a simple way to get all this but every thing i have used i not giving me right data.any help would be thankful.

Upvotes: 0

Views: 245

Answers (2)

pratik
pratik

Reputation: 64

To get companies registered with plan 'A' and companies with plan 'B'. Take object of plan, and then through following relationship code, you will get count of companies. This is join concept. eg. @plan is object of Plan 'A'. then @plan.companies.count.

I suggest to use "polymorphic association" concept.

Upvotes: 1

Samiron
Samiron

Reputation: 5317

You need to insert new records through the association. Here is a related link that might help. how to add records to has_many :through association in rails

But a Pseudo-code will be like

1. You have a company object
2. you will have company.subscriptions
3. Insert new Plan objects in company.subscriptions
4. Save the data.

If you are still facing problem, I will try to add some code example.

Upvotes: 1

Related Questions