ruby on rails - Nested form sends :id instead of friendly_id in POST request -
ruby on rails - Nested form sends :id instead of friendly_id in POST request -
routes.rb:
resources :courses, path: '' resources :students resources :awards end end
students/show.html.erb
<%= form_for [@course, @student, @award] |f| %> <div class="field"> <%= f.label :ticket %><br> <%= f.text_field :ticket %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
models/student.rb
belongs_to :course has_many :awards, dependent: :destroy extend friendlyid friendly_id :uuid, use: [ :slugged, :finders ]
controllers/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
controllers/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
now, expect post request sent form this:
post "/3344-2334/students/hh36-f4t4-545t/awards"
but server getting
post "/3344-2334/students/5/awards"
from receive error:
activerecord::recordnotfound in awardscontroller#create
because gets :id (5) instead of friendly_id :uuid (hh36-f4t4-545t).
why parent (courses) getting friendly_id :title kid (students) getting unfriendly :id? new rails , lost.
you can override default returned param pupil model give uuid instead of id. seek set in pupil model.
def to_param uuid end
you can take @ this, may help understand how friendlyid works.
ruby-on-rails ruby-on-rails-4 friendly-id
Comments
Post a Comment