Ruby on Rails, two models in one form

后端 未结 5 1160
我在风中等你
我在风中等你 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:28

    You can achieve that using nested attributes :

    patient.rb

    class Patient < ActiveRecord::Base
      attr_accessible :age, :name,  :pretreatments_attributes, :diagnosiss_attributes
      has_many :pretreatments
      has_many :diagnosiss
    
      accepts_nested_attributes_for :pretreatments
      accepts_nested_attributes_for :diagnosiss
    end
    

    patients_controller.rb

    def show
        @patient = Patient.find(params[:id])
        @patient.pretreatments.build
        @patient.diagnosiss.build
        respond_to do |format|
          format.html # show.html.erb
          format.json { render json: @patient }
        end
      end
    

    patients/show.html.erb:

    <%= form_for @patient do  |f|%>
        

    Pretreatments:

    <%= f.fields_for :pretreatments do |field| %> <%= field.label "Content" %>
    <%= field.text_field :content %> <% end %>

    Diagnosis:

    <%= f.fields_for :diagnosiss do |field| %> <%= field.label "Content" %>
<%= field.text_field :content %> <% end %> <%=f.submit %> <% end %>

And that all

提交回复
热议问题