2015-08-13 29 views
0

控制器:這是我不開心的部分。Rails 4:有沒有更好的方法來構建對象:has_many通過?

def new 
    @incident = Incident.new 
    @patient = Patient.find(params[:patient]) 
end 

# This looks like trouble waiting to happen. 
def create 
    @patient = Patient.find(params[:incident][:patient]) 
    @incident = Incident.new(incident_params) 
    @incidentcases = current_user.incidentcases.build(:incident => @incident,:patient => @patient) 

    respond_to do |format| 
     if @incident.save 
     @incidentcases.save 
     format.html { redirect_to @incident, notice: 'Incident was successfully created.' } 
     format.json { render :show, status: :created, location: @incident } 
     else 
     format.html { render :new } 
     format.json { render json: @incident.errors, status: :unprocessable_entity } 
     end 
    end 
end 

型號:

class Incident < ActiveRecord::Base 
     has_many :incidentcases 
     has_many :users, through: :incidentcases 
     has_many :patiens, through: :incidentcases 
    end 
    class Incidentcase < ActiveRecord::Base 
     belongs_to :user 
     belongs_to :patient 
     belongs_to :incident 
    end 

    class User < ActiveRecord::Base 
     has_many :incidentcases 
     has_many :incidents, through: :incidentcases 
    end 

    class Patient < ActiveRecord::Base 
     has_many :incidentcases 
     has_many :incidents, through: :incidentcases, dependent: :destroy 

     accepts_nested_attributes_for :incidents, reject_if: :all_blank, allow_destroy: true 
    end 

它是在控制器創建對象的一種更好的方式,並有軌道照顧它。

感謝

回答

0

你試過:

@patient = Patient.find(params[:incident][:patient]) 
@patient.incidents.build(incident_params) 
if @patient.save 

它應該會自動建立連接的記錄。

+0

謝謝, 這實際上是一種工作。 我需要添加current_user它雖然我可以通過另一個聯合建立像我在上面的代碼,但它是抱怨: @ patient.incidents.build(incident_params,:user => current_user) 錯誤參數的數量(2代表0..1)。嗯。生病繼續挖掘。 – lmcdougall

+2

@lmcdougall你有一​​個錯誤,因爲'build'方法需要一個散列參數,即'attributes = {}',你可以合併這個散列並使用'user_id',而不是像這樣'@patient.incidents.build incident_params.merge(user_id: current_user.id)' –

0

非常感謝您的幫助。每當你們幫助我時,我都會繼續學習。

以上更改爲上面的代碼給了我所查找的內容。

def create 
    @patient = Patient.find(params[:incident][:patient]) 
    @incident = Incident.new(incident_params) 
    @incidentcases = current_user.incidentcases.build(:incident => @incident,:patient => @patient) 

    respond_to do |format| 
     if @incidentcases.save 

這包括我缺少的user_id,它自動創建所有連接。

相關問題