使用自定义URL(例如http:// localhost:3000 / education_informations / new?user_id = 10)在新页面上呈现错误

我正在尝试使用新操作http:// localhost:3000 / education_informations / new?user_id = 10传递查询参数,并在其上设置表单validation。 当表单提交失败,所以它的显示错误,但url更改为http:// localhost:3000 / education_informations所以我想同样自定义url并使用user_id传递查询参数。 请帮我

控制器代码给出如下

def create @edu_info = EducationInformations.new(educational_params) if @edu_info.save #flash[:notice] = 'Vote saved.' redirect_to @edu_info else render 'new' end end 

您可以将参数传递给form_for如下所示,即使在表单提交失败后也将user_id保留在URL中

 <%= form_for @edu_info, :url => { :action => :create, :user_id => @user.id } %> 

要么

 <%= form_for @edu_info, :url => { :action => :create, :user_id => current_user.id } %> 

如果@user未初始化。

资源

我假设教育信息将永远被用户所知。 所以要创建路线,你应该做:

在路线文件中:

 resources :users do resources :education_informations end 

那么这将做的是创建我在评论中指定的路线。 像这样将是路线:

 user_education_informations GET /users/:user_id/education_informations(.:format) education_informations#index POST /users/:user_id/education_informations(.:format) education_informations#create new_user_education_information GET /users/:user_id/education_informations/new(.:format) education_informations#new edit_user_education_information GET /users/:user_id/education_informations/:id/edit(.:format) education_informations#edit user_education_information GET /users/:user_id/education_informations/:id(.:format) education_informations#show PATCH /users/:user_id/education_informations/:id(.:format) education_informations#update PUT /users/:user_id/education_informations/:id(.:format) education_informations#update DELETE /users/:user_id/education_informations/:id(.:format) education_informations#destroy users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/:id/edit(.:format) users#edit user GET /users/:id(.:format) users#show PATCH /users/:id(.:format) users#update PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy 

因此,对于新的eudcation信息表单,您需要提供此路径new_user_education_information_path(user) ,其中user将是单击的用户。

您可以在此处获取更多信息: http : //guides.rubyonrails.org/routing.html#nested-resources

希望这可以帮助。

您可以将redirect_to与url参数一起使用。

#create操作中,您将获得当前的user_id参数:

 user_id = params[:user_id] 

如果你想redirect_to @edu_info并保留params,你可以通过redirect_to方法的options hash设置它们:

 redirect_to @edu_info(user_id: user_id) 

这对你有意义吗?