[POST] [Ruby on Rails] 上的路由错误
-
27-09-2019 - |
题
现在我正在 Rails 中构建一个项目管理应用程序,以下是一些背景信息:
现在我有两种模型,一种是用户,另一种是客户端。客户端和用户具有一对一的关系(客户端 -> has_one 和用户 -> own_to 这意味着外键位于用户表中)
因此,我想做的是,一旦您添加客户端,您实际上可以向该客户端添加凭据(添加用户),为此,所有客户端都会显示在该客户端名称旁边的链接,这意味着您实际上可以为该客户端创建凭据。
因此,为了做到这一点,我使用了一个助手,就像这样的助手链接。
<%= link_to "Credentials",
{:controller => 'user', :action => 'new', :client_id => client.id} %>
这意味着他的 url 将像这样构造:
http://localhost:3000/clients/2/user/new
通过为客户端创建 ID 为 2 的用户。
然后将信息捕获到控制器中,如下所示:
@user = User.new(:client_id => params[:client_id])
编辑:这就是我目前在视图/控制器和路由中的内容
我不断收到此错误:没有路由与“/clients//user”与 {:method=>:post} 匹配
路线
ActionController::Routing::Routes.draw do |map|
map.resources :users
map.resources :clients, :has_one => :user
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
控制器
class UsersController < ApplicationController
before_filter :load_client
def new
@user = User.new
@client = Client.new
end
def load_client
@client = Client.find(params[:client_id])
end
def create
@user = User.new(params[:user])
@user.client_id = @client.id
if @user.save
flash[:notice] = "Credentials created"
render :new
else
flash[:error] = "Credentials created failed"
render :new
end
end
看法
<% form_for @user, :url => client_user_url(@client) do |f| %>
<p>
<%= f.label :login, "Username" %>
<%= f.text_field :login %>
</p>
<p>
<%= f.label :password, "Password" %>
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation, "Password Confirmation" %>
<%= f.password_field :password_confirmation %>
</p>
<%= f.submit "Create", :disable_with => 'Please Wait...' %>
<% end %>
解决方案 2
我通过在创建客户端时使用嵌套属性(包括用户模型)解决了这个问题。而且它工作完美。
如果你们中的任何人需要更多信息,这里有两个截屏视频帮助我想出了解决方案:
其他提示
您的表单标签错误,您正在发布到 /users
没有 :client_id
.
尝试这个:
<% form_for @user, :url => {:controller => 'users', :action => 'new', :client_id => @client.id} do |f| >
或者,您可以使用嵌套资源:
配置/routes.rb
map.resources :clients do |clients|
clients.resources :users
end
控制器
class UsersController < ApplicationController
before_filter :load_client
def load_client
@client = Client.find(params[:client_id])
end
# Your stuff here
end
看法
<% form_for [@client, @user] do |f| %>
不隶属于 StackOverflow