Prev | Current Page 346 | Next

Brad Ediger

"Advanced Rails"

We open app/models/product.rb, which was a very straightforward
ActiveRecord model:
class Product < ActiveRecord::Base
end
We change this to an equivalently simple ActiveResource model, backed by the web
service that we have set up:
class Product < ActiveResource::Base
self.site = "http://localhost:4000/"
end
RESTful Rails | 229
Now we have to fix a small glitch due to differences between ActiveRecord and
ActiveResource. Unlike ActiveRecord objects, ActiveResource objects don??™t know
their potential set of attributes when they are initialized (as that would take a web
service call to determine). In our client application, the ProductsController#new
action sets up an empty Product with the following:
@product = Product.new
On the server, @product is an ActiveRecord::Base object. That statement fetches
some metadata about the products table??™s columns, their data types, and their constraints.
On the other hand, on the client, @product is an ActiveResource::Base
object. Initializing it with .new does not contact the server, and therefore it knows
nothing about its own attributes.
To resolve this, we will cheat a little. The app/views/products/new.erb view accesses
the product??™s attributes with text_field and the like:
<% form_for(:product, :url => products_path) do |f| %>


Name

<%= f.text_field :name %>


...
<% end %>
These methods are helpful; they will use the @product object if it is present (and use
its attribute values as default values in the text boxes).


Pages:
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358