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
它是在控制器创建对象的一种更好的方式,并有轨道照顾它。
感谢
谢谢, 这实际上是一种工作。 我需要添加current_user它虽然我可以通过另一个联合建立像我在上面的代码,但它是抱怨: @ patient.incidents.build(incident_params,:user => current_user) 错误参数的数量(2代表0..1)。嗯。生病继续挖掘。 – lmcdougall
@lmcdougall你有一个错误,因为'build'方法需要一个散列参数,即'attributes = {}',你可以合并这个散列并使用'user_id',而不是像这样'@patient.incidents.build incident_params.merge(user_id: current_user.id)' –