如何从 Sinatra 中的 post 路由获取 id

How to get id from post route in Sinatra

我有一个正在创建学生的工厂。所有必填字段都在工厂中填写和创建。当我 post 一个新学生时,我从来没有得到那个学生,只是在工厂创建的那个?如何从 POST?

中获取新学生的 ID

students.rb

FactoryGirl.define do
factory :student do
sequence(:id)
sequence(:first_name){|n| "Tom"}
sequence(:last_name) {|n| "Dick"}
sequence(:password) {|n| "test"}
sequence(:email){ |n| "person#{n}@example.com" }
school
end
end

student_spec.rb

require File.dirname(__FILE__) + '/spec_helper'

describe 'admin' do
 before :all do
@student=FactoryGirl.create(:student)
end
it 'should save student information' do
params={
    post:{
        first_name: 'Abraham',
        last_name: 'Lincoln',
        address: '1400 Pennsylvania Ave.',
        city: 'Washington',
        state: 'D.C.',
        zip: '11111',
        email: 'alincoln@whitehouse.gov',
        password: 'I cant tell a lie',
        major: 'Law',
        level: 'Graduate',
        employment: 'President',
        participation: 'Yes',
        participation_research: 'No',
        what_doing_now: 'Watching a Play',
        ethnicity: 'White',
        eth_other: 'none',
        education_level: 'Doctorate',
        hometown: 'Springfield, IL',
        twitter_handle: '@TheRealAbe',
        facebook_url: 'therealabe',
        prior_education: 'None',
        prior_AS: 'None',
        prior_BS: 'None',
        prior_MS: 'None',
        prior_Other: 'None',
        awards_honors: 'Ended Civil War',
        scholarships: 'Full',
        other_inbre_funding: 'yes',
        deleted: 'false'
    }
}
post '/admin/students/add/', params, {'rack.session'=>{student_id:@student.id, admin_authorized:true}}
updated_student = Student.get(@student.id)

expect(updated_student.first_name).to eql('Abraham')
#expect(updated_student.last_name).to eql('Dick')
#expect(updated_student.address).to eql('1400 Pennsylvania Ave.')
end

end

如果没有看到路由,我无法确定,但在我看来,您调用了 POST 两次,一次在路由中,一次在参数哈希中。但是,如果没有看到您的路线,我无法确定这是否是一个问题。

另一个想法来自阅读您的规范。您是要创建新学生 (POST) 还是要编辑学生?如果您正在尝试编辑现有学生,这可能是指按照 RESTful 约定的单独路线、PUT 或 PATCH。上面说了,POST路由不需要id,正是因为它是在创建一个新的student,它会在这个地方创建id,而id是由数据库设置的,而不是手动设置的。

参考以上内容:http://guides.rubyonrails.org/v2.3.11/routing.html

我希望这至少指向了正确的方向。 :D