Я новичок в программировании и Rails, и я работаю над процессом регистрации приложения, над которым я работаю. У меня есть модели user
и profile
. В рамках процесса регистрации я смешиваю поля для user
и profile
, поэтому я использую вложенные формы.
Я пытаюсь заставить вложенные формы работать в контроллере, который обрабатывает мои статические страницы, потому что я хочу инициировать процесс регистрации на домашней странице.
Процесс регистрации может быть инициирован двумя способами: непосредственно с домашней страницы или пропущен на домашней странице и инициирован в представлении / signup / skip.
Мой InfoController (где существует файл home.html.erb
с формой):
def home
if logged_in?
redirect_to current_user.profile
end
end
Вложенная форма в home.html.erb
:
<%= form_for(:profile, :url => 'signup', :html => {:id => 'homepage'}) do |f| %>
<p class="hometext">I'm </p>
<div>
<%= f.label :first_name, :placeholder => 'First name' %>
<%= f.text_field :first_name, :size=> 8, :id => "profile[first_name]" %>
</div>
<div>
<label for="profile[last_name]">Last name</label>
<%= f.text_field :last_name, :size=> 8, :id => "profile[last_name]" %>
</div>
<%= f.fields_for :user do |f| %>
<p class="hometext">. My email is
<div>
<label for="user[email]">Email</label>
<%= f.text_field :email, :size=> 13, :id => "user[email]" %>
</div>
<% end %>
<p class="hometext">. I want to </p>
<div>
<label for="user[stat]">put stat here</label>
<%= f.text_field :stat, :size=> 13, :id => "user[stat]" %>
</div>
<p class="hometext">when I grow up. </p>
<div id="button">
<%= submit_tag 'Join', :class => 'button orange' %>
</div>
<% end %>
Модель профиля:
class Profile < ActiveRecord::Base
attr_accessible :first_name, :last_name ...
belongs_to :user
accepts_nested_attributes_for :user
end
Модель пользователя:
class User < ActiveRecord::Base
attr_accessor :password, :email
accepts_nested_attributes_for :profile
has_one :profile, :dependent => :destroy
end
По какой-то причине, когда я ввожу данные в форме, я перенаправлен в / login, который находится в Routes.rb
как Sessions#new
. Итак, вот SessionsController:
class SessionsController < ApplicationController
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to user.profile, :notice => "Logged in successfully"
else
flash.now[:alert] = "Invalid login/password. Try again!"
render :action => 'new'
end
end
И последнее, но не менее важное: ProfilesController:
class ProfilesController < ApplicationController
def new
@profile = Profile.new
end
def create
@profile = Profile.new(params[:profile])
if @profile.save
redirect_to profile_path, :notice => 'User successfully added.'
else
render :action => 'new'
end
end
С сервера:
Started POST "/signup" for 127.0.0.1 at Sat Aug 27 10:36:50 -0400 2011
DEPRECATION WARNING: You are using the old router DSL which will be removed in Rails 3.1. Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/. (called from /Users/me/Desktop/app/config/routes.rb:1)
Processing by ProfilesController#new as HTML
Parameters: {"commit"=>"Join", "profile"=>{"last_name"=>"...", "user"=> {"test"=>"...", "email"=>"..."}, "first_name"=>"..."}, "authenticity_token"=>"u82Jom5PV+5BeTLZ5qQENxQiY1lcyFiXR4aNC7NR+5g=", "utf8"=>"\342\234\223"}
Redirected to http://localhost:3000/login
Completed 302 Found in 35ms
Started GET "/login" for 127.0.0.1 at Sat Aug 27 10:36:51 -0400 2011
Processing by SessionsController#new as HTML
Rendered layouts/_header_out.html.erb (0.5ms)
Rendered layouts/_footer.html.erb (2.2ms)
Rendered sessions/new.html.erb within layouts/application (32.1ms)
Completed 200 OK in 40ms (Views: 39.0ms | ActiveRecord: 0.0ms)
Обновление: файл маршрутов (по крайней мере, соответствующие части) ниже:
match '/login' => "sessions#new", :as => "login"
match '/signup', :to => 'profiles#new'
match 'skip/signup', :to => 'info#signupskip'
match 'skip/profiles/new', :to => 'profiles#newskip'
root :to => 'info#home'
resources :users
resources :profiles
resources :info
Может кто-нибудь помочь мне понять это? Будем благодарны за любые рекомендации о том, как заставить это работать и делать это в соответствии с лучшими практиками.