Forum: Ruby on Rails Creating/Updating Models from text/xml Requests

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5c262b1a445eb969fd2d411316f5365e?d=identicon&s=25 MaggotChild (Guest)
on 2009-03-14 02:34
(Received via mailing list)
I'm curious how others would deal with this situation.

In my case, I have:

class Package
  has_many :deliveries
end

class Delivery
  belongs_to :package
  belongs_to :region
end

class Region
  has_many :deliveries
end

And accept XML requests in the following manner:

<package>
  <name>Good Shipment<name>
  <!-- snip other fields -->
  <deliveries>
    <delivery>
      <status>Failure</status>
      <region>
  <name>US</name>
      </region>
    </delivery>
    <delivery>
      <status>Unknown</status>
      <region>
  <name>FR</name>
      </region>
    </delivery>
  </deliveries>
</package>

Now, my controller would look something like this ugly beast:

class PackagesController
  def create
    if package = params[:package]
      package = Package.find_or_initialize_by_name(package)
      if deliveries = package.delete(:deliveries)
         deliveries.each do |d|
             region = d.delete(:region)
             region = Region.find_or_create_by_name(region[:name])
             break if region.nil?
             package.deliveries.create(region)
             package.deliveries[-1].region = region
         end
      end
    end
    #save and more...
  end
end

As one can see, this is horrible for several reasons. One of the big
ones being request validation and error handling.

Overriding package.from_xml  is an option, but I find myself thinking
that I should be validating against request.body with say a DTD, as
opposed to picking apart the params hash. (Though I'll have to pick it
apart anyways to create the models...)

Then I find my self thinking that creating a course grained validation
method like a DTD is stupid since I have my fine grain validation
logic within the given models.

Yes, I've heard of ROXML.

Any thoughts?
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2009-03-14 03:06
(Received via mailing list)
MaggotChild wrote:

> And accept XML requests in the following manner:
>
> <package>
>   <name>Good Shipment<name>
>   <!-- snip other fields -->
>   <deliveries>
>     <delivery>
>       <status>Failure</status>
>       <region>


If you try this from_xml...

   http://gist.github.com/75525

...I think it would clear the make-work out of the way, allowing you to
focus on
the validations. Tell me if you get stuck - I wrote it for your exact
situation,
but it can't validate automatically.
This topic is locked and can not be replied to.