0

现在我正在 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 %>
4

2 回答 2

0

您的表单标签错误,您发布到/users没有:client_id.

试试这个:

<% form_for @user, :url => {:controller => 'users', :action => 'new', :client_id => @client.id} do |f| >

或者,您可以使用嵌套资源:

配置/路由.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| %>
于 2010-06-14T16:30:21.460 回答
0

我在创建客户端时通过使用嵌套属性解决了这个问题,包括用户模型。它完美无缺。

如果你们中的任何人需要更多信息,这里是帮助我提出解决方案的两个截屏视频:

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/196-nested-model-form-part-2

于 2010-07-16T18:15:21.387 回答