3

我是 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
我的用户模型列表:有 _one :profile

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

我在配置文件表中有一个 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 入门应用程序中的评论连接到帖子的方式相同。这是我的配置文件控制器的相关部分。如果有帮助,我可以提供全部内容:

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 用例,但我不确定哪些部分是错误的。在此先感谢您的帮助!

4

3 回答 3

4

创建用户时,客户端将被重定向newProfileController没有id. 您需要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,因为如果没有用户,配置文件就无法存在。

于 2009-08-19T11:14:05.853 回答
0

为了可用性,个人资料应该是用户模型的一部分,或者您应该一次性创建您的帐户和至少您个人资料的基础,作为我注册的用户,然后必须填写我认为我会填写的另一张表格很生气。

这样做的好处是,无论哪种方式,你都可以用一种形式做到这一点。我会看一下关于复杂表单的 railscasts ,如果你能处理非常少的财务支出,那么Mastering Rails Forms上的实用程序员系列将是一个完全的赢家。

于 2009-08-19T11:04:37.120 回答
0

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

于 2009-12-16T07:15:24.710 回答