0

多くのユーザーがいるトップレベルのアカウントの実装に取り​​組んでいます。

私はこの質問の解決策に取り組んでいます: Deviseでアカウントテーブルとユーザーテーブルの両方を使用してください

何が機能するか:

ユーザーが登録フォーム(下記)を送信すると、ユーザーとアカウントが必要に応じて作成されます。

動作しないもの:

ユーザーはredirect_toaccounts_pathの前に認証されていません。認証するには、ユーザーは[ログイン]をクリックして、サインアップしたばかりの資格情報を入力する必要があります。代わりに、リダイレクトの前にユーザーを認証する必要があります。

私はこれに数時間取り組んでおり、いくつかのアプローチを試しましたが、何も機能していないようです。

ユーザー/アカウントが正常に作成された後、誰かがユーザーを認証するためのコードを手伝ってくれませんか。ありがとう!

モデル

class Account < ActiveRecord::Base
  has_many :users, :inverse_of => :account, :dependent => :destroy
  accepts_nested_attributes_for :users
  attr_accessible :name, :users_attributes
end

class User < ActiveRecord::Base
  belongs_to :account, :inverse_of => :users
  validates :account, :presence => true
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable
  attr_accessible :email, :password, :password_confirmation, :remember_me
end

ルート

resources :accounts, :only => [:index, :new, :create, :destroy]
controllers/accounts_controller.rb

コントローラー

class AccountsController < ApplicationController

  def new
    @account = Account.new
    @account.users.build # build a blank user or the child form won't display
  end

  def create
    @account = Account.new(params[:account])
    if @account.save
      flash[:success] = "Account created"
      redirect_to accounts_path
    else
      render 'new'
    end
  end

end

ビュー/アカウント/new.html.erbビュー

<h2>Create Account</h2>

<%= form_for(@account) do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>

  <%= f.fields_for :users do |user_form| %>
    <div class="field"><%= user_form.label :email %><br />
    <%= user_form.email_field :email %></div>
    <div class="field"><%= user_form.label :password %><br />
    <%= user_form.password_field :password %></div>
    <div class="field"><%= user_form.label :password_confirmation %><br />
    <%= user_form.password_field :password_confirmation %></div>
  <% end %>

  <div class="actions">
    <%= f.submit "Create account" %>
  </div>
<% end %>
4

2 に答える 2

1

ユーザーを手動でサインインする必要があります。アカウント コントローラーsign_in(user)では、サインインuserする実際のUserモデル レコードが必要です。

問題は、1 つのアカウントと複数のユーザーの関係があることです。したがって、何らかの方法で単一のユーザーにアクセスする必要があります。たとえば、次のようになります。

  def create
    @account = Account.new(params[:account])
    if @account.save
      sign_in(@account.users.first)
      flash[:success] = "Account created"
      redirect_to accounts_path
    else
      render 'new'
    end
  end
于 2013-03-12T15:10:43.507 に答える
1

追加する必要があります

  before_filter :authenticate_user!, :except => [:new,:create]

残りのアクションに認証を提供するために、アカウント コントローラーへ

于 2013-03-12T15:19:34.143 に答える