Search code examples
ruby-on-railsrubydevisemigrationmodels

Adding multiple objects to a user in rails


I previously asked a vague question about adding multiple objects to a user table. I got a really good answer from heading_to_tahiti but I am having trouble implementing it.

I have my user migration all set up with devise. I wanted to be able to make a form that allows a user to add a medications to their account. He suggested making a medications model and other stuff using scaffolding and making a medication column in the user model. I tried this and its on the right track but I'm confused on how the medications model does anything and how the medication column stores multiple medications.

I am a newbie at rails and especially at doing anything server related, so any help would be appreciated.

I want the end result to be this web portal showing all of the users' medications and allowing them to do the CRUD tasks on them. I hope this isn't too far-reached and definitely don't feel obligated to answer the whole question, I know this is a lot to ask for.

Here is the previous question How can I add additional columns to a Users table with rails and devise gem?

And my app currently https://i.sstatic.net/zWGfS.jpg

Thanks


Solution

  • What you want is a one-to-many relationship. One user can have many medications. Create a model for your medications that has a field called user_id. In medications.rb:

    class Medication < ActiveRecord::Base
      belongs_to :user
    end
    

    and in users.rb:

    class User < ActiveRecord::Base
      has_many :medications
    end
    

    As long as your medications model has a field called user_id, Rails is smart enough to know that when you call myuser.medications you want all of the Medication records where user_id = myuser.id. You can read more here.