Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How to add additional attributes to the join table in HABTM and fetch that when getting association values?

ruby-on-rails relationship HABTM

  • Please log in to reply
6 replies to this topic

#1 Logesh

Logesh

    Signalman

  • Members
  • 14 posts

Posted 03 September 2013 - 08:33 AM

I have two models User and Category. Consider the following code

 

 

class User < ActiveRecord::Base

 

    has_and_belongs_to_many :categories

    accepts_nested_attributes_for :categories, :allow_destroy => true

    alias_method :categories=, :categories_attributes=

end

 

 

class Category < ActiveRecord::Base

    has_and_belongs_to_many :users

end

 

I want to create categories when it is not already present in the category table. If the category is already present in the table then i need to refer the id of the category to the user in the join table.

And consider i need to add a field say type in the join table along with the reference where i need to add the type of the category.

 

Say for example

 

 

user table:

 

1, sample_user

2, test_user

 

category table:

 

1, category1

2, category2

 

 

categories_users:

 

category_id       user_id      type

      1                     1            type1

      2                     1            type2

      1                     2            type2

      1                     2            type1

 

 

And when getting the category of users i need to get the category object along with the type of the category within the category object.

 

How can i do this? please help me                   



#2 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 03 September 2013 - 11:50 AM

And consider i need to add a field say type in the join table along with the reference where i need to add the type of the category.

 

I think you need to use has many :through  relationships instead of has_and_belongs_to_many  for your particular situation, since you need to also work on their relationship table.   

 

http://guides.rubyon...ion_basics.html

has_many_through.png


  • Kelli Shaver, james and Logesh like this

#3 Logesh

Logesh

    Signalman

  • Members
  • 14 posts

Posted 04 September 2013 - 04:44 AM

Thankyou. I understand what you are saying but i want to know how the appointment date is saved in the join table in your example. consider the following 

 

 

curl -H 'Content-Type: application/json' -H 'Accept: application/json' -X PUT http://localhost:3000/users/2.json -d "{\"user\":{\"name\":\"sample_user\", \"category\":[{\"category_name\":\"sdhsjksh\", \"category_id\":ds443we186}, {\"category_name\":\"Accenture\", \"category_id\":4er454354459}]}}"

 

In the above shown, i have sent the categories for the user and as you said the categories is saved in the categories table and its refernce is saved in the join table and using through i can fetch. But how can i send the type(same like appointment_date). How can i fetch as well?

 

Sorry if my question is unclear.Please help me.



#4 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 04 September 2013 - 05:19 AM

In the physician example above, to access appointment_date,  you can do

physician.appointments.first.appointment_date

You need to be pointed to a record (that's why I used .first, or .last, or use a specific record id, or iterate through it) before I can access appointment_date

 

if you have iterators, loop through

physician.appointments.each do |p|
    puts  p.appointment_date
end

to access the appointment_date. 

 

If you want to access the patients, you do 

physician.appointments.each do |p|
    puts  p.patient.name
end

If you need to set the appointment_date, you just do

p.appointment_date = 'whatever'  inside your iterator

or

physician.appointments.first.appointment_date = 'new value'

then do a 

physician.appointments.first.save

I find it very useful playing with the Rails Console, and a pgadmin GUI editor working through these associations. You can see immediately what is being returned and if the generated SQL command is correct or is what you expected. You can verify using the GUI editor the data being saved or retrieved in your actual database. 

 

 

Hey, I'm still a newb so I'll let the experts confirm this answer. 



#5 Logesh

Logesh

    Signalman

  • Members
  • 14 posts

Posted 04 September 2013 - 05:31 AM

I can able to access the categories of user simply as format.json{ render json: @user.as_json(:include => [:categories]) } 

 

But what i need is how to insert the appointment date in the appointment table when patient is created. And also how can i fetch the appointment date of the patient along with patient when i get the physician. And tell me how if there is a patient already in the patient table then i need to save the id of the patient in the appointment table but with different appointment date.



#6 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 04 September 2013 - 11:52 AM

But what i need is how to insert the appointment date in the appointment table when patient is created.

 

 

Try this. 

physician.patients.create(name: 'patient-name', appointment_date:'1/2/13') 

Rails will take care of filling in the foreign keys in the appointment table automatically. 

 

And also how can i fetch the appointment date of the patient along with patient when i get the physician.

 

See my earlier example. 

 

 

 

And tell me how if there is a patient already in the patient table then i need to save the id of the patient in the appointment table but with different appointment date.     

 

If you construct your database access  like this.... 

physician.patient.appointments.create(.....)  

Rails will take care of filling in the foreign keys in your relationship table.  

 

i.e. don't do it manually like this: 

Patients.create(...parameters-go-here....) 

then do a 

Appointments.create(... parameters-go-here....) 

If you do it separately like above, then you'd have to fill in the foreign keys id values.  

 

 

Just open up Rails console and experiment from there, and play with accessing and saving data on the different tables. 



#7 Logesh

Logesh

    Signalman

  • Members
  • 14 posts

Posted 06 September 2013 - 05:19 AM

Can you please explain me how i can send the appointment values through json so that the value of the appointment date is automatically saved in the join table as it does for saving the physician_id and patient_id.

"{\"physician\":{\"name\":\"sample_user\", \"patients_attributes\":[{\"name\":\"sdhsjksh\"}]}}"

In the above example i send the patient information when creating or updating the Physician. This itself creates a entry in the patient table and the reference is saved in the appointment table. Similarly how can i send the appointment_date along with this so that the appointment_date is saved in the join table as it does now for saving patient_id and physician_id.







Also tagged with one or more of these keywords: ruby-on-rails, relationship, HABTM

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users