1

创建数据模型对象以便我可以创建表单的正确方法是什么。当我第一次创建对象时,它没有具有有效属性数据的参数数据,因此 build_ 返回一个无效对象并且 rails 抛出 500 Internal Server Error。

这是我正在查看的内容:

楷模

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 结果

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

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

更新 为了更清楚地说明这一点,问题@cred = current_user.build_credentials是返回零。我raise @cred.inspect在创建@cred 后直接拨打电话以验证其为零。当我看到form_for(@cred)...@cred 只是一个 nil 对象时,它会呕吐undefined method 'model_name' for NilClass:Class

4

1 回答 1

1

为什么凭据属于控制器?它应该属于用户,如果使用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.erbinapp/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
于 2012-11-16T07:01:22.167 回答