通过外键链接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
我可以看到Practer_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
}
答案 0 :(得分:1)
如果我理解您的问题,您可以在将时间卡保存在控制器中之前设置@timecard.practitioner = @practitioner
。您可以这样做,因为belongs_to
gives you一个practioner=
方法“分配关联对象,提取主键,并将其设置为外键。”
答案 1 :(得分:0)
我假设一个从业者有很多时间卡,所以你应该可以做类似的事情
# practitioner.rb
has_many :timecards
# controller
@practitioner = Practitioner.find(params[:practitioner_id])
@timecard = @practitioner.timecards.build(params[:timecard])
设置关联将负责为您设置外键。