ruby-on-rails-3 - Ruby on Rails 嵌套路由和form_for以及使用has_one和belongs_to的模型

  显示原文与译文双语对照的内容

如何用嵌套路由映射has_one模型,以及如何在rest式数据库中为/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



views/profiles/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>



控制器: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 sign_in(user) cookies.permanent [:remember_token] = user.remember_token 自身。current_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



时间: 原作者:

配置文件表是否具有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



你真的希望用户创建他的配置文件? 通常情况下,当用户 register 。

原作者:
...