Home > Mobile >  Adding a field to a model using a foreign key in Ruby On Rails
Adding a field to a model using a foreign key in Ruby On Rails

Time:06-01

I have a table called family that has a key called survey_id that is a foreign key to the survey table. Is there a way to return a survey model with data from the family table.

CodePudding user response:

Specify association in Family model belongs_to :survey. Then you can retrieve associated model instance_of_family_model.survey Recommend reading this https://guides.rubyonrails.org/association_basics.html

CodePudding user response:

You can specify survey association on Family model

class Family < ApplicationRecord
  belongs_to :survey
end

And than you can get survey on any instance of Family model

@family = Family.find(1)
@family.survey
  • Related