实例化关联的模型输入可用于填充模型属性(has_one)

时间:2012-11-16 06:14:28

标签: ruby-on-rails associations belongs-to has-one

创建数据模型对象的正确方法是什么,以便我可以创建表单。当我第一次创建对象时,它没有带有效属性数据的params数据,因此build_返回一个无效对象,rails会抛出500内部服务器错误。

以下是我正在看的内容:

模型

class Credentials < ActiveRecord::Base
belongs_to user
...
class User < Active ::Base
has_one :credentials, :dependent => :destroy
...

控制器

def new
@cred = current_user.build_credentials 
    render 'edit'
end
    ...

查看

<%= form_for(@cred) do |f| %>

日志

Started GET "/credentials" for 127.0.0.1 at 2012-11-16 00:43:26 -0500
Processing by CredentialsController#new as HTML
  [1m[35mUser Load (0.3ms)[0m  SELECT `users`.* FROM `users` WHERE `users`.`remember_token` = 'oWGXC2dmcg2sRyg5mvA6fw' LIMIT 1
  [1m[36mUser Load (0.3ms)[0m  [1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1[0m
  [1m[35mCredentials Load (0.4ms)[0m  SELECT `credentials`.* FROM `credentials` WHERE `credentials`.`user_id` = 1 LIMIT 1
  [1m[36m (0.1ms)[0m  [1mBEGIN[0m
  [1m[35m (0.1ms)[0m  COMMIT
  Rendered credentials/edit.html.erb within layouts/application (8.8ms)
Completed 500 Internal Server Error in 100ms

rsec results

undefined method `credentials_index_path' for #<#<Class:...

凭据模型有许多验证要求,因此new创建的对象无效(我可以在控制台中确认),因为填充的唯一值是外键,在本例中为user_id 。但是在控制台中我可以建立@credentials变量,并在下一个命令中分配所有属性。在Web服务器中,500错误使得无法遵循相同的方法。

更新 为了更清楚,问题是@cred = current_user.build_credentials返回零。 我在创建@cred之后直接调用raise @cred.inspect来验证它的nil。当我到达视图form_for(@cred)... @cred只是一个零对象,所以它与undefined method 'model_name' for NilClass:Class

1 个答案:

答案 0 :(得分:1)

为什么Credentials属于控制器?它应该属于用户,如果你使用has_one关联,你应该使用凭证的单数名词:

<强>模型

class Credential < ActiveRecord::Base
belongs_to user
...
class User < Active ::Base
has_one :credential, :dependent => :destroy

<强>控制器

在你的控制器中,如果你想为表单创建新对象,你只需要:

def new
  @cred = current_user.build_credential 
end

def create
  @cred = current_user.build_credential(params[:cred])
  if @cred.save
    # what you do when creating object success
  else
    # what you do when creating object failed
  end
end

查看

new.html.erb app/views/credentials/文件夹中,创建表单:

<%= form_for @cred do |f| %>
...
<% end %>

要链接到new.html.erb页面,请在视图中创建link_to

<%= link_to 'New Credential', new_credential_path %>

<强>路线

如果您想使用RESTful路由,请在routes.rb中添加您没有的凭据资源:

resources :credentials