我有一个注册过程:
user = User.new
user.email = ...
user.password = ...
user.profile = Profile.new
user.profile.save
user.save
在我的应用中,我通过InfoController
在主页上启动注册过程来处理静态页面。由于主页上的表单混合了user
和profile
模型,因此我使用的是嵌套模型表单。但是,当我提交表单时,我被重定向到了错误的地方。谁能帮我弄清楚我做错了什么?
Routes.rb文件:
match '/login' => "sessions#new", :as => "login"
match '/signup' => 'profiles#new', :as => "signup"
match 'skip/signup', :to => 'info#signupskip'
match 'skip/profiles/new', :to => 'profiles#newskip'
root :to => 'info#home'
root :to => "questions#index"
resources :users
resources :profiles
resources :info
resource :session
resources :session
ProfilesController:
class ProfilesController < ApplicationController
before_filter :authenticate
def new
@profile = Profile.new
end
def name
puts "#{user.profile.first_name} #{user.profile.last_name}"
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
...
UsersController:
class UsersController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
def new
@user = User.new
end
def index
@user = User.all
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to profile_path, :notice => 'User successfully added.'
else
render :action => 'new'
end
end
最后,带有嵌套模型的表单:
<%= 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[goal]">ex: be President</label>
<%= f.text_field :goal, :size=> 13, :id => "user[goal]" %>
</div>
<p class="hometext">when I grow up. </p>
<div id="button">
<%= submit_tag 'Join', :class => 'button orange' %>
</div>
<% end %>
答案 0 :(得分:2)
以下路线不正确:
match '/signup' => 'profiles#new', :as => "signup"
在form_for
中,您指定的是:profile
。默认情况下,Rails将POST
设置为profiles#create
。由于您传递了:url => 'signup'
,因此表单实际上是POST
到/signup
,通过上述路线映射到profiles#new
。但是,new
操作只是设置表单 - 这是您首次启动的操作。话虽这么说,正确的路线应该是:
match '/signup' => 'profiles#create', :as => "signup"
事实上,如果你想让它变得更好,那应该是这样的:
post '/signup' => 'profiles#create', :as => "signup"
此外,由于您使用的是指定路线(在路线中传递as
),因此您应该在:url => signup_path
中使用form_for
。
暂时不说:我不太确定你的模特是什么样的,但我可能会同意Kleber的观点。它似乎更直观,应该是form_for :user
。