New to associations

If I have a has_many assication such as:
patient->has_many-> treatments.

Should I be able to do something like this:

patient = Patient.create(trtmt_code: ‘AAA’)

**assume that trtmt_code is in the treatments table ***

Should I be able do that?

I keep getting ‘sanitize_forbidden_attributes’ :frowning:

Rails 4.2.7


Hey Ed,

You’re not able to do this in Rails. There are a couple of options:

  1. Lookup the treatment first:

    treatment = Treatment.find_by_code(‘AAA’)

  2. Set a custom attr_accessor in the Patient model:

    attr_accessor :trtmt_code

    def trtmt_code=(code)
    self.treatment = Treatment.find_by_code(‘AAA’)

    def trtmt_code

Also, minor note: it’s convention in Rails not to shorten attribute
names, so I would suggest renaming trtmt_code to treatment_code

Hope this helps!


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs