2015-08-13 78 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,它自动创建所有连接。

相关问题