簡體   English   中英

在[POST] [Ruby on Rails]上路由錯誤

[英]Routes error on [POST] [Ruby on Rails]

現在,我正在Rails中構建一個項目管理應用程序,這是一些背景信息:

現在我有2個模型,一個是User,另一個是Client。 客戶端和用戶具有一對一的關系(客戶端-> has_one和用戶->屬於_to,這意味着它在用戶表中的外鍵)

因此,我要嘗試執行的操作是,一旦添加客戶端,您便可以向該客戶端實際添加憑據(添加用戶),以便顯示所有客戶端,並在該客戶端名稱旁邊顯示一個鏈接,這意味着您可以實際為該客戶端創建憑據。

因此,為了做到這一點,我使用了一個幫助器,鏈接到了這樣的幫助器。

<%= link_to "Credentials", 
        {:controller => 'user', :action => 'new', :client_id => client.id} %>

這意味着他的網址將如下所示:

http://localhost:3000/clients/2/user/new

通過為他的ID為2的客戶端創建用戶。

然后像這樣將信息捕獲到控制器中:

@user = User.new(:client_id => params[:client_id])

編輯:這是我目前在我的視圖/控制器和路線中所擁有的

我不斷收到此錯誤:沒有路由將{/ method =>:post}與“ / clients // user”匹配

路線

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 %>

您的表單標簽是錯誤的,您要發布到/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| %>

我在創建客戶端時通過使用嵌套屬性(包括用戶模型)解決了這一問題。 它可以完美地工作。

如果你們需要更多信息,下面的兩個截屏視頻幫助我提出了解決方案:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM