這裏有很多,特別是對於Rails 4.0和Rails 3.x.我是嵌套路由的新手,我發現它非常困難,特別是對於表單。表單中的第一個參數不能包含零或在導軌中爲空4.0
所以,我有以下幾點:
路線
resources :users do
resources :api_keys, path: '/developmentcenter'
end
這裏的關係是:用戶具有這樣的API密鑰屬於用戶許多API密鑰。
控制器
class ApiKeysController < ApplicationController
before_action :authenticate_user!
def new
@user = User.find(params[:user_id])
@api_key = ApiKey.new(:user => @user)
end
def index
@user = User.find(params[:user_id])
@api_key = @user.api_keys
end
def create
@user = User.find(params[:user_id])
@api_key = ApiKey.new(create_new_api_key)
create_api_key(@api_key, @user)
end
def destroy
@user = User.find(params[:user_id])
destroy_api_key(@user)
end
private
def create_new_api_key
params.permit(:api_key, user_attributes: [:id])
end
end
上面是非常基本的。 create_api_key
是一種在保存時執行某些操作的方法,或者在保存失敗時執行其他操作。雖然destroy_api_key
只需找到基於用戶id的api密鑰並刪除它,在成功和失敗時做一些事情。
所以現在讓我們創建一個表單 - 它有一個用於創建API密鑰的按鈕。
<h2>Create a new Key</h2>
<%= form_for ([@user, @api_keys]) do |f| %>
<p class="button"><%= f.submit "Generate API Key" %></p>
<% end %>
所有我們需要的是一個提交按鈕,用戶點擊後,會爲在其中將記錄用戶一個新的API密鑰
別急,我們有一個錯誤:
First argument in form cannot contain nil or be empty
這個錯誤在發生:
<%= form_for ([@user, @api_keys]) do |f| %>
所以 - 我已經看過的堆棧問題每一個(最好)處理這個錯誤,我已經改變了我的控制器基於幾個,你看到上面的。我甚至在rails手冊中查看了表單助手文檔。
我無法弄清楚這一點。