Friday, 9 August 2013

Checking for nil value using :before_save

Checking for nil value using :before_save

In my view I have a dropdown of people within an organisation that a
ticket can be assigned to.
<label for="assigned_support_id">Assigned To</label>
<%= select( "ticket", "assigned_support_id",
Person.find_admin_and_support.collect {|p| ["#{p.name}", p.id]},
{:include_blank => "&lt; Unassigned &gt;"} ) %>
Because the blank inserted above has no value, if that option is selected
then the ticket will remain assigned to the same person.
I've considered creating an 'Unassigned' person in the database but that
will probably be quite complicated having that 'person' belong to every
organisation....
I also considered using JavaScript to manipulate the DOM and give it a
value but I wanted to do this the 'Rails Way' so I've come up with the
following:
ticket.rb
before_save :check_unassigned
...
private
def check_unassigned
if self.assigned_support_id.nil? or defined?(self.assigned_support_id)
self.assigned_support_id = 0
end
end
The nil check didn't seem to do anything so I added the defined check but
the problem with that is that every time I reassign a ticket to another
user it the table will be updated with 0 so something isn't quite right
and I'm not sure what the bug is.
I also considered updating the update method in my controller by checking
the [:params][:assigned_support_id] but thought the above was a neater
solution.

No comments:

Post a Comment