Ruby on Rails, two models in one form

后端 未结 5 1239
我在风中等你
我在风中等你 2021-01-31 05:57

I have two very similar models Pretreatment and Diagnosis, that belong to the model Patient:

class Pretreatment < ActiveRecord::Base
  belongs_to :patient
  a         


        
5条回答
  •  天命终不由人
    2021-01-31 06:08

    Use fields_for for the associated models.
    There should be no square brackets arround the parameters of fields_for

    In your code example, I cannot find the relation between Patient and Diagnosis, and the plural of diagnosis is diagnoses, you can specify this in config/initializers/inflections.rb:

    ActiveSupport::Inflector.inflections do |inflect|
      inflect.irregular 'diagnosis','diagnoses'
    end
    

    So your Patient model should contain

    class Patient < ActiveRecord::Base
      attr_accessible :age, :name, :city, :street, :number
      has_many :diagnoses
    end
    

    And you can write in your form:

     
    <%= f.label :content %>
    <%= f.text_field :content %>
    <%= fields_for(@patient, @patient.diagnoses.build) do |u| %>
    <%= u.label :content %>
    <%= u.text_field :content %>
    <% end %>
    <%= f.submit %>

提交回复
热议问题