Rails 4:有没有更好的方法来构建对象:has_many through?

时间:2015-08-13 18:11:30

标签: ruby ruby-on-rails-4 has-many-through

  

控制器:这是我不高兴的部分。

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

它必须是在控制器中创建对象的更好方法,并让rails为您处理它。

由于

2 个答案:

答案 0 :(得分:0)

你试过了吗?

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

它应该自动构建连接记录。

答案 1 :(得分: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,它自动构建了所有连接。