From 8c10764be79ee1f9b020766fdea7c69d74f2ab81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20Deest?= Date: Thu, 18 Mar 2010 15:01:24 +0100 Subject: [PATCH] Adding a 'build' method to the ActiveResource class, to build a new resource from the default values of the remote site. This fixes two issues: - When using the RESTful form_for helper with new ActiveResource instance, creating fields for uninitialized attributes would result in a NoMethodError exception. - Remote default values can now be used to populate forms. Usage: Simply call Resource.build instead of Resource.new when using ActiveResource. [#4155 state:committed] --- activeresource/lib/active_resource/base.rb | 34 ++++++++++++++++++++++++++++ 1 files changed, 34 insertions(+), 0 deletions(-) diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index b841108..16dda18 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -625,6 +625,22 @@ module ActiveResource "#{prefix(prefix_options)}#{collection_name}/#{id}.#{format.extension}#{query_string(query_options)}" end + # Gets the new element path for REST resources. + # + # ==== Options + # * +prefix_options+ - A hash to add a prefix to the request for nested URLs (e.g., :account_id => 19 + # would yield a URL like /accounts/19/purchases/new.xml). + # + # ==== Examples + # Post.new_element_path + # # => /posts/new.xml + # + # Comment.collection_path(:post_id => 5) + # # => /posts/5/comments/new.xml + def new_element_path(prefix_options = {}) + "#{prefix(prefix_options)}#{collection_name}/new.#{format.extension}" + end + # Gets the collection path for the REST resources. If the +query_options+ parameter is omitted, Rails # will split from the +prefix_options+. # @@ -653,6 +669,19 @@ module ActiveResource alias_method :set_primary_key, :primary_key= #:nodoc: + # Builds a new, unsaved record using the default values from the remote server so + # that it can be used with RESTful forms. + # + # ==== Options + # * +attributes+ - A hash that overrides the default values from the server. + # + # Returns the new resource instance. + # + def build(attributes = {}) + attrs = connection.get("#{new_element_path}").merge(attributes) + self.new(attrs) + end + # Creates a new resource instance and makes a request to the remote service # that it be saved, making it equivalent to the following simultaneous calls: # @@ -933,6 +962,7 @@ module ActiveResource def initialize(attributes = {}) @attributes = {}.with_indifferent_access @prefix_options = {} + load(attributes) end @@ -1346,6 +1376,10 @@ module ActiveResource self.class.element_path(to_param, options || prefix_options) end + def new_element_path + self.class.new_element_path(prefix_options) + end + def collection_path(options = nil) self.class.collection_path(options || prefix_options) end -- 1.7.0