创建数据模型对象以便我可以创建表单的正确方法是什么。当我第一次创建对象时,它没有具有有效属性数据的参数数据,因此 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