嵌套模型表格无法正常工作 - 需要查明POST / GET重定向

时间:2011-08-29 00:05:03

标签: ruby-on-rails-3 nested-forms

我有一个无法正常运行的嵌套模型表单。 POST到了正确的位置,但GET重新路由我。所以我想知道是否有人可以帮助解释我做错了什么。

我有两个模型:UserProfile。它们的代码如下:

用户:

class User < ActiveRecord::Base
  attr_accessor :password, :email
  has_one :profile, :dependent => :destroy
  accepts_nested_attributes_for :profile
  ...
end

配置文件:

class Profile < ActiveRecord::Base
  attr_accessible :first_name, :last_name, etc.
  belongs_to :user
  accepts_nested_attributes_for :user
  ...
end

从两个模型中新建/创建:

class UsersController < ApplicationController
  def new
    @user = User.new
    if logged_in?
      redirect_to current_user.profile
    end
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      redirect_to signup_path, :notice => 'User successfully added.'
    else
      render :action => 'new'
    end
  end

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

  def index
    @profile = current_user.profile
  end

我的注册(两步过程)混合模型,因为我说我在我的用户new.html.erb文件中使用了嵌套模型表单。下面的代码form_forf.fields_for

<%= form_for(:user, :url => signup_path, :html => {:id => 'homepage'}) do |f| %>
<%= f.fields_for :profile do |f| %>

现在当我在表单中输入数据时,我的routes.rb文件似乎POST到正确的位置(/signup,因此可以进一步填写配置文件),但是GET将我路由到/login

的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 => 'users#new'
resources :users
resources :profiles

rails server

Started POST "/signup" for 127.0.0.1 at Sun Aug 28 19:54:11 -0400 2011
  Processing by ProfilesController#new as HTML

Started GET "/login" for 127.0.0.1 at Sun Aug 28 19:54:11 -0400 2011
  Processing by SessionsController#new as HTML
Rendered sessions/new.html.erb within layouts/application (32.1ms)

我想知道问题是否在我的layouts/application文件中,特别是此代码:

<% if logged_in? %>
  <%= render 'layouts/header_in' %>
<% else %>
  <%= render 'layouts/header_out' %>
<% end %>

任何人都可以帮我解释一下我做错了什么吗?

更新

我删除了`layouts / application'中的if / else参数,但它仍然被重定向。所以我回想起发生了什么事。

1 个答案:

答案 0 :(得分:1)

我认为你的问题与HTTP协议的固有问题(尽管可能没有问题)有关。您无法将重定向返回到POST请求。替代方案包括从第一个控制器操作中调用另一个方法,或直接从该操作呈现正确的页面,或者两者的混合。