routes.rb中:
resources :courses, path: '' do
resources :students do
resources :awards
end
end
学生/ show.html.erb
<%= form_for [@course, @student, @award] do |f| %>
<div class="field">
<%= f.label :ticket %><br>
<%= f.text_field :ticket %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
模型/ student.rb
belongs_to :course
has_many :awards, dependent: :destroy
extend FriendlyId
friendly_id :uuid, use: [ :slugged, :finders ]
控制器/ students_controller.rb
before_action :set_course
def show
@student = @course.students.find_by_uuid! params[:id]
@award = @student.awards.build
@awards = @student.awards.load.where.not('id' => nil) # exclude empty row
end
private
def set_course
@course = Course.find_by_title!(params[:course_id])
end
def student_params
params.require(:student).permit(:email, :uuid, :grade_point_average, :course_id)
end
控制器/ awards_controller.rb
before_action :set_variables
def create
@award = @student.awards.build award_params
if @award.save
redirect_to course_student_path(@course, @student.uuid)
else
redirect_to course_student_path(@course, @student.uuid)
end
end
private
def set_variables
@course = Course.find_by_title! params[:course_id]
@student = @course.students.find_by_uuid! params[:student_id]
end
def award_params
params.require(:award).permit(:ticket, :student_id)
end
现在,我希望从表单发送的POST请求看起来像这样:
POST "/3344-2334/students/hh36-f4t4-545t/awards"
但这就是服务器的用途
POST "/3344-2334/students/5/awards"
我从中收到错误:
ActiveRecord::RecordNotFound in AwardsController#create
因为它获取:id(5)而不是friendly_id :uuid(hh36-f4t4-545t)。
为什么父母(课程)获得了friendly_id :title ,但是孩子(学生)获得了不友好的:id ?我是Rails的新手,完全迷失了。
答案 0 :(得分:2)
您可以覆盖学生模型的默认返回参数,以便为您提供uuid而不是id。试着把它放在你的学生模型中。
def to_param
uuid
end
您还可以查看this,它可以帮助您了解friendlyId的工作原理。