现在我正在 Rails 中构建一个项目管理应用程序,这里有一些背景信息:
现在我有2个模型,一个是用户,另一个是客户端。Clients 和 Users 是一对一的关系(client -> has_one 和 user -> belongs_to 这意味着它在 users 表中的外键)
所以我想要做的是,一旦您添加了一个客户端,您实际上可以向该客户端添加凭据(添加一个用户),为此,所有客户端都显示在该客户端名称旁边的链接,这意味着您实际上可以为该客户端创建凭据。
因此,为了做到这一点,我使用了一个助手链接到这样的助手。
<%= 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 %>