I have a relationship model that tracks customers (users) of shops in a has_many :through
association. I\'m having trouble with my ShopsController
If I understand your use case, a shop has many customers and a customer frequents many shops.
The result of doing this the Rails way is you can retrieve customers belonging to a specific shop just by using an instance of that shop and calling shop.customers
You can find a specific customer for that shop, by calling shop.customers.find(:id)
If you try calling for another shops customer, you get a ActiveRecord::RecordNotFoundError
Ditto the other way round. To retrieve the shops a customer frequents, ideally you want customer.shops
etc as above. To add a new shop to a customer, use customer.shops.create("Arkwrights Dairy")
As Shadwell stated your current efforts to create the structure are far more complicated than you need. And you do not set this up through the controllers, only through the models.
Models, 2 only
class Shop < ActiveRecord::Base
has_and_belongs_to_many :customers
class Customer < ActiveRecord::Base
has_and_belongs_to_many :shops
Migrations, 3
class SampleMigration < ActiveRecord::Migration
def change
create_table :shops do |t|
t.string :name
end
create_table :customers do |t|
t.string :name
end
create_table :customers_shops, id: false do |t|
t.belongs_to :customer
t.belongs_to :shop
end
end
end
Add more detail to the models as you see fit, but this should be enough to establish the relationships. Things to watch are the plurals, shop verse shops is important. Shop the class and belongs_to :shop are both singular. References to many shops is plural and tables hold many shops so are also plural. And the join table has to be in alphabetical order, customers_shops not shops_customers.
Once set up, run your migrations then try.
shop = Shop.create(name: "Dairy")
=> #
shop.customers.create(name: "Bill")
=> #
customer = Customer.find(1)
=> #
customer.shops
=> [#]
Note that shops returns an array. Access the first element using customer.shops[0] or alternatively customer.shops.find(1) to retrieve the shop using its :id
Hopefully that will give you the foundation you need :-)