在Rails中关联两个模型(用户和配置文件)

我是Rails的新手。 我正在构建一个具有用户模型和配置文件模型的应用程序。

我想将这些模型关联起来:
– 用户创建帐户后,他会自动发送到“创建个人资料”页面,他创建的个人资料仅连接到该特定用户。
– 只有拥有该配置文件的用户才能对其进行编辑。

我使用nifty_generators生成了用户模型。 当用户点击提交创建帐户时,我会将其重定向到“新配置文件”视图以创建配置文件。 我是通过编辑用户控制器中的重定向路径来完成的。 用户控制器如下所示:

def create @user = User.new(params[:user]) if @user.save session[:user_id] = @user.id flash[:notice] = "Thank you for signing up! You are now logged in." redirect_to new_profile_path else render :action => 'new' end end 

这是有效的,但问题是应用程序似乎没有意识到该配置文件已连接到该特定用户。 我能够创建配置文件,但配置文件和用户之间似乎没有关系。

我的个人资料模型列表:belongs_to:user
我的用户模型列表:has _one:profile

我的routes.rb文件列出了以下内容:
map.resources:users,:has_one =>:profile
map.resources:个人资料

我在配置文件表中有一个user_id外键。 我的架构如下所示:

 create_table "profiles", :force => true do |t| t.integer "user_id" t.string "name" t.string "address1" t.string "address2" t.string "city" t.string "state" t.string "zip" t.string "phone" t.string "email" t.string "website" t.text "description" t.string "category" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "username" t.string "email" t.string "password_hash" t.string "password_salt" t.datetime "created_at" t.datetime "updated_at" end 

为了尝试将配置文件连接到用户,我使用以下内容更新了profiles_controller.rb文件,我基本上是从Rails入门指南中推断出来的。 我的想法是,在我的应用程序中,配置文件以与在Rails Getting Started应用程序中相同的方式连接到用户,注释连接到post。 这是我的配置文件控制器的相关部分。 如果有帮助,我可以提供整件事:

 def new @user = User.find(params[:user_id]) @profile = @user.profile.build end def create @user = User.find(params[:user_id]) @profile = @user.profile.build(params[:profile]) if @profile.save flash[:notice] = 'Profile was successfully created.' redirect_to(@profile) else flash[:notice] = 'Error. Something went wrong.' render :action => "new" end 

结束

在对配置文件控制器进行这些更新后,现在当我在帐户创建屏幕上提交时,我被重定向到一个错误页面,其中显示:

ProfilesController中的ActiveRecord :: RecordNotFound #new
找不到没有ID的用户

这一切似乎都是一个非常简单的Rails用例,但我不确定哪些部分是错误的。 在此先感谢您的帮助!

创建用户时,客户端将重定向到ProfileController没有idnew操作。 您需要在参数中明确传递用户的id 。 将引用传递给整个对象,而不仅仅是id,这是一个习惯用法。

 # app/controllers/users_controller.rb def create # ... redirect_to new_user_profile_path(:user_id => @user) # ... end 

请注意,我使用的是new_user_profile_path而不是new_profile_path 。 前者是您在routes.rb定义的嵌套资源。 您应该删除map.resources :profiles因为没有用户,配置文件不能存在。

为了便于使用,配置文件应该是用户模型的一部分,或者您应该一次性创建您的帐户和至少您的配置文件的基础,作为我注册的用户,然后必须填写另一种forms我认为我会非常恼火。

这样做的好处是,无论哪种方式,您都可以使用一种forms。 我会看一下复杂forms的轨道广播,如果你能处理一笔非常适度的财务支出,那么关于Mastering Rails Forms的实用程序员系列就是一个总赢家。

因为user_id不存在或未在配置文件数据库中创建。 创建用户时