开发者

Calling two methods from one controller in nested model form

Through other posts on SO I've learned that my sign-up process using a nested model form is flawed in that I create a new User, then redirect to create its Profile. Here is the process:

user = User.new
user.email = ...
user.password = ...
user.profile = Profile.new
user.profile.first_name = ...
...
user.profile.save
user.save

It seems as if one solution is to initiate the profile method from within the UsersController create(?) action, so that I POST to both models(?开发者_C百科) then redirect to a page with a form to fill out the rest of the profile.

But I'm not entirely sure how to do that, as I am new to programming/Rails. So can anyone give me guidance on how to introduce the Profile method within the UsersController? I gave it a go but don't think it's correct. Code for both Users/ProfilesController below:

User:

def new
  @user = User.new
  @user.profile = Profile.new
end

def index
  @user = User.all
end

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

Profile:

def new
  @user.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

Routes.rb:

match '/signup' => 'profiles#new', :as => "signup"
get "signup" => "profiles#new", :as => "signup"
root :to => 'users#new'
resources :users
resources :profiles

My nested model form (the relevant parts):

<%= form_for(:user, :url => { :action => :create }, :html => {:id => 'homepage'}) do |f| %>
  <%= f.text_field :email, :size=> 13, :id => "user[email]" %>
  <%= f.fields_for :profile do |f| %>
  <% end%>
<% end %>

If anyone could help me I'd greatly appreciate it.


You should have something like this in your models:

class User < ActiveRecord::Base
  has_one :profile
  accepts_nested_attributes_for :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

...of course all backed up with proper migrations. Then while building up a form you can use fields_for helper. Here is slightly modified example from docs:

<%= form_for @user do |user_form| %>
  Email: <%= user_form.text_field :email %>
    <%= user_form.fields_for :profile do |profile_fields| %>
      First Name: <%= profile_fields.text_field :first_name %>
  <% end %>
<% end %>

And update your user and his profile in the controller in one go, thanks to accepts_nested_attributes_for :profile declaration in your model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜