Howdy,
First off, awesome work on DM, and congrats on v1.0, guys!
I'm hoping another DM user out there can share their approach to this.
I sifted through the mailing list archives without much luck.
I'm used to using ActiveRecord, and I think I'm used to writing my
code one way. Since I'm moving my new projects to DM however, I'd like
to learn better ways of using DM. I'm using DM v1.0 with Rails v3.0-
beta4, although I think this could apply to other frameworks. I also
have dm-validations, dm-types, dm-migrations, dm-constraints, dm-
timestamps, and dm-rails activated.
Let's assume a User and Ticket model:
class User
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
has n, :tickets
end
class Ticket
include DataMapper::Resource
property :id, Serial
property :title, String, :required => true
property :body, Text
belongs_to :user, :required => false
end
The idea is to allow--but not require--a Ticket to be assigned to a
User (Ticket.belongs_to :user). As such, in the add/edit ticket form,
I have the following drop down:
<select id="ticket_user_id" name=ticket[user_id]">
<option value="">Please select a user...</option>
<option value="1">Ripta Pasay </option>
</select>
A portion from my controller code:
@ticket = Ticket.new(params[:ticket])
if @ticket.save
flash[:notice] = "Ticket successfully created."
redirect_to tickets_path
else
render :action => 'new'
end
When a user is selected, for example user ID 1, the ticket is assigned
correctly (i.e. @ticket.user_id in the controller will contain the
integer value 1).
However, when no user is selected, the resource returns the error
"User ID must be an integer". Digging in, this is because DM is passed
"" (an empty string) as the value of user_id. It turns out that DM
will coerce (or simply call #to_i on) values such as the string "1"
into the integer 1, but won't automatically coerce "" into nil.
At first, I tried suppressing automatic validation:
without_auto_validations do
belongs_to :user, :required => false
end
which didn't really do anything. I also tried explicitly specifying
a :user_id property:
without_auto_validations do
property :user_id, Integer
end
which simply made #save silently fail (i.e. @ticket.save == false, but
@ticket.errors has no errors).
At the moment, I'm forced to add a check in my controller:
params[:ticket].delete(:user_id) if params[:ticket]
[:user_id].blank?
but I'm hoping I'm simply missing a more elegant ("proper"?)
solution. :-D
I'd love to write up some self-contained test cases if anyone is
interested.
Cheers,
Ripta
--
You received this message because you are subscribed to the Google Groups
"DataMapper" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/datamapper?hl=en.