Hi,
I have two tables as

employee
    id  int primary key,
    purchase_order_product int,
    bundle int

fabric_bundles
   id int primary key,
   purchase_order_product int,
   bundle int,
   quantity

I want to make assciation between employee and fabric_bundles via purchase_order_product and bundle

I'm not sure what you really want here. Would an employee can have multiple fabric bundles and a fabric bundle can belong to multiple employees (many to many)? If so, what you need is has_and_belongs_to_many :employees keywords in fabric_bundle model and has_and_belongs_to_many :fabric_bundles in employee models. Then do a db migration in order to force rails to automatically generate a table which consists of only employee & fabric bundle ID. You will not need purchase_order_product or any other foreign key field at all.

If a fabric bundle can belong to only an employee but not vice versa (1 to many), then you just need has_many :fabric_bundles keyword in employee model and belongs_to :employee in fabric_bundle model. Still, you don't need the purchase_order_product field in both but rather employee_id field inside fabric_bundles table.

Hope this help...

Thanks
I will definetly try this. See normally association based on primary keys.
In my case two table association with pair of columns not with a single column and without creating third table.
i.e. purchase_order_product and bundle

In Rails, association will automatically create a relationship for you. You need to think of each row is an object. If you create an association between 2 tables, you need to be explicit of how 2 tables are associated. Yes, using primary keys is the way to associate tables together; however, in Rails, it makes use of the association and make it easier to deal with. For example, see below...

employees
    id  int primary key,
    bundle int
fabric_bundles
   id int primary key,
   employee_id int      # Rails will use it as foreign key
   bundle int,
   quantity

 *Plese note that ALL tables in Rails are required their plural name

Now what you need to do is to add association keywords in both model files. Once you did that, you can simply use them in your Rails code.

e.g.
# SQL query: SELECT * FROM employees WHERE id=1
employee = Employee.find(id:, 1)  # Rails version (3?)4+

# SQL query: SELECT * FROM fabric_bundles WHERE employee_id=1
# or whatever the current employee object's id is
employee_fabric_bundles = employee.fabric_bundles

As you can see that you do not need to directly call through fabric_bundles table query because the association you have established in their models will handle that for you.

Hope this help clearing it up a bit.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.