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)' –