通过外键链接 rails 对象的最佳方法是什么?这是我的例子。从业者有一张考勤卡(收集每天的工作时间)。我想把从业者的身份证放在预约上以显示这一点:
来自 routes.rb
resources :locations do
resources :practitioners, only: [:new, :create]
end
resources :practitioners, except: [:new, :create] do
resources :timecards, except: :delete
resources :appointments
end
timecard.rb - 你可以在这里看到我强制 timecard.practitioner_id 为 3,但这是一个蛮力测试工作。
class Timecard < ActiveRecord::Base
belongs_to :practitioner
attr_protected :id
before_save :set_practitioner_id
def set_practitioner_id
if self.practitioner_id.blank?
self.practitioner_id = 3
end
end
end
从我的控制器...
def create
@practitioner = Practitioner.find(params[:practitioner_id])
@timecard = Timecard.create(params[:timecard])
respond_to do |format|
if @timecard.save
format.html { redirect_to @practitioner, notice: 'Timecard was successfully created.' }
format.json { render json: @timecard, status: :created, location: @timecard }
else
format.html { render action: "new" }
format.json { render json: @timecard.errors, status: :unprocessable_entity }
end
end
end
我可以看到practice_id = 3 的参数(这是我想要使用的),我只是不知道如何在代码中访问它。
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"DIp4R31McXnBNP4NB06KDTzV+8lLcWvxbq1w9J+Z1+M=",
"timecard"=>{
"hours_worked"=>"2",
"activity_date(1i)"=>"2013",
"activity_date(2i)"=>"3",
"activity_date(3i)"=>"20",
"practitioner_id"=>"",
"location_id"=>"1"
},
"commit"=>"Create Timecard",
"practitioner_id"=>"3" <== this is what I want to use
}