What is the right way to create a data model object so that I can create a form. When I first create the object it doesn’t have params data with the valid attribute data so the build_ returns an invalid object and rails throws 500 Internal Server Error.
Here’s what I’m looking at:
Models
class Credentials < ActiveRecord::Base
belongs_to user
...
class User < Active ::Base
has_one :credentials, :dependent => :destroy
...
Controller
def new
@cred = current_user.build_credentials
render 'edit'
end
...
View
<%= form_for(@cred) do |f| %>
Log
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:...
The credentials model has many verification requirements so the object that is being created by new is invalid (I can confirm this in the console) as the only value that is populated is the foreign key, in this case user_id. However in the console I can establish the @credentials variable and the in the next command assign all the attributes. In the web server the 500 error makes it impossible to follow the same approach.
Update
To make this more clear, the problem is that the @cred = current_user.build_credentials is returning a nil.
I put an raise @cred.inspect call directly after creating @cred to validate that its nil. When I get to the view form_for(@cred)... @cred is just a nil object so it pukes with undefined method 'model_name' for NilClass:Class
Why Credentials belongs to controller? It should belongs to user, and if you use
has_oneassociation, you should use singular noun of credential:Model
Controller
In your controller, if you want create new object for form, you only need:
View
In your
new.html.erbinapp/views/credentials/folder, create your form:To link to
new.html.erbpage, in your view create alink_to:Routes
If you want to use RESTful route, In your
routes.rb, add resources for credential you don’t have: