【发布时间】:2015-08-14 11:40:06
【问题描述】:
控制器:这是我不满意的部分。
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 为您处理它。
谢谢
【问题讨论】:
标签: ruby ruby-on-rails-4 has-many-through