I’m trying to use ActiveModel instead of ActiveRecord for my models because I do not want my models to have anything to do with the database.
Below is my model:
class User
include ActiveModel::Validations
validates :name, :presence => true
validates :email, :presence => true
validates :password, :presence => true, :confirmation => true
attr_accessor :name, :email, :password, :salt
def initialize(attributes = {})
@name = attributes[:name]
@email = attributes[:email]
@password = attributes[:password]
@password_confirmation = attributes[:password_confirmation]
end
end
And here’s my controller:
class UsersController < ApplicationController
def new
@user = User.new
@title = "Sign up"
end
end
And my view is:
<h1>Sign up</h1>
<%= form_for(@user) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation, "Confirmation" %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
But when I load this view in the browser, I am getting an exception:
undefined method 'to_key' for User:0x104ca1b60
Can anyone please help me with this?
Many thanks in advance!
I went rooting around the Rails 3.1 source to sort this out, I figured that would be easier than searching anywhere else. Earlier versions of Rails should be similar. Jump to the end if tl;dr.
When you call
form_for(@user), you end going through this:And since
@useris neither a String nor Object, you go through theelsebranch and intoapply_form_for_options!. Insideapply_form_for_options!we see this:Pay attention to that chunk of code, it contains both the source of your problem and the solution. The
dom_idmethod callsrecord_key_for_dom_idwhich looks like this:And there’s your call to
to_key. Theto_keymethod is defined byActiveRecord::AttributeMethods::PrimaryKeyand since you’re not using ActiveRecord, you don’t have ato_keymethod. If you have something in your model that behaves like a primary key then you could define your ownto_keyand leave it at that.But, if we go back to
apply_form_for_options!we’ll see another solution:So you could supply the
:asoption toform_forto generate a DOM ID for your form by hand:You’d have to make sure that the
:asvalue was unique within the page though.Executive Summary:
to_keymethod that returns it.:asoption toform_for.