使用has_one和belongs_to的嵌套路由和form_for和模型

时间:2012-07-04 22:13:59

标签: ruby-on-rails ruby-on-rails-3 controllers form-for nested-resources

如何使用嵌套路由映射has_one模型以及如何在RESTful数据库之后为/localhost:3000/users/1/profile/new,html.erb添加form_for?

用户有一个个人资料。

模型

class Profile < ActiveRecord::Base
  attr_accessible :name, :surname
  belongs_to :user
end

class User < ActiveRecord::Base
  attr_accessible :email, :email_confirmation, :password, :password_confirmation
  has_secure_password
  has_one :profile, dependent: :destroy
end

  resources :users do
    resources :profiles      (note: has_one profile)
    resources :progress_charts
    resources :calories_journals
  end

视图/简档/ new.html.erb

<h1>About You</h1>
<div class="row">
  <div class="span6 offset3">
    <%= form_for(@profile) do |f| %>
    <%= render 'shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :surname %>
      <%= f.text_field :surname %>

      <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
    <% end %>
  </div>
</div>

controller:Profiles_controller.rb 我发现了两个错误,因为我不太明白它为什么不起作用。

class ProfilesController < ApplicationController
def index
end

def show
end

  def new
  #  @user = User.find(params[:id]) # Error message: Couldn't find User without an ID
  #  @profile = @user.build_profile()

    @profile = current_user.build_profile(params[:id]) # Error message: unknown attributes: user_id
  end

  def edit
  end

  def create
  end

  def update
  end

  def destroy
  end
end

助手:SessionHelper(用于说明current_user)     模块SessionsHelper         def sign_in(用户)         cookies.permanent [:remember_token] = user.remember_token         self.current_user = user       端

  def signed_in?
    !current_user.nil?
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user?(user)
    user == current_user
  end

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  def sign_out
    self.current_user = nil
    cookies.delete(:remember_token)
  end

  def signed_in_user
    unless signed_in?
      store_location
      redirect_to signin_path, notice: "Please sign in."
    end
  end
end

1 个答案:

答案 0 :(得分:5)

您的个人资料表是否具有user_id属性?

在您的路线中,个人资料应该是单数,因为用户有一个个人资料:

resources :users do
    resource  :profile
    resources :progress_charts
    resources :calories_journals
end

指向用户个人资料的路线为users/:user_id/profile(而不是users/:user_id/profile/:id

在profiles_controller中:

@profile = current_user.build_profile(params[:id]) # why params[:id]?
#it should just be
@profile = current_user.build_profile()
@user = User.find(params[:user_id])

表格如下:

form_for [@user, @profile] do |f|...
end

你真的希望用户像这样创建他的个人资料吗?通常,您会在用户注册时创建配置文件。