0

現在、レールでプロジェクト管理アプリを構築しています。背景情報は次のとおりです。

現在、2 つのモデルがあり、1 つはユーザーで、もう 1 つはクライアントです。クライアントとユーザーには 1 対 1 の関係があります (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])

編集:これは、現在ビュー/コントローラーとルートにあるものです

次のエラーが発生し続けます: No route match "/clients//user" with {: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

クライアントを作成するときに、ネストされた属性を使用し、ユーザーモデルを含めることで、これを解決しました。そしてそれは完璧に動作します。

誰かがより多くの情報を必要とする場合に備えて、これが私が解決策として思いつくのを助けた2つのスクリーンキャストです:

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 に答える
0

フォーム タグが間違っています。./usersなしで に投稿してい:client_idます。

これを試して:

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

または、ネストされたリソースを使用できます。

config/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| %>
于 2010-06-14T16:30:21.460 に答える