我想爲新的用戶對象創建一個虛擬帳戶。每當用戶在我的應用程序註冊時,它應該自動爲他創建一個帳戶。未從嵌套表單保存到數據庫
但是發生了什麼事情,我在數據庫中保存新用戶,但不是新帳戶。我也不知道在這種情況下尊重MVC模式設計的最佳方式是什麼。我害怕複製代碼或讓一個控制器執行兩個工作。
的註冊表格,具有嵌套資源(和它的建立在色器件頂部)
<h2>Sign up</h2>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :name %><br />
<%= f.text_field :name %></div>
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<p>Account name</p>
<%= f.fields_for :account do |builder| %>
<fieldset>
<%= builder.label :title %>
<%= builder.text_field :title %>
</fieldset>
<% end %>
<div><%= f.submit "Sign up" %></div>
<% end %>
<%= render "devise/shared/links" %>
我的用戶模型:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :accounts
accepts_nested_attributes_for :accounts
end
和我的帳戶型號:
class Account < ActiveRecord::Base
belongs_to :user
end
我的用戶控制器:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
sign_in @user
##flash[:success] = "Welcome to the HighTide!"
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation, accounts_attributes: [:id, :title])
end
end
終於賬戶控制器:
class AccountsController < ApplicationController
def new
@account = @user.accounts.new
end
def create
@account = current_user.accounts.new(account_params)
if @account.save
redirect_to '/'
end
end
private
def account_params
params.require(:account).permit(:title, :user_id, products_attributes: [:id, :title, :units], bookings_attributes: [:id, :name, :check_in, :check_out])
end
end
編輯:
的routes.rb文件
Hightide::Application.routes.draw do
devise_for :users, path_names: {sign_in: "login", sign_out: "logout"}
resources :users do
resources :accounts
end
resources :sessions
match '/users/:user/edit', to: 'users#edit', via: [:post, :get]
devise_scope :user do
root to: 'static_pages#home'
match '/sessions/user', to: 'devise/sessions#create', via: :post
end
你在哪裏定義'User.new_guest'? – Donovan
我更新了帖子。我在模型上定義了它,但我放棄了它。 – tvieira