<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Santiago Palladino &#187; Rails</title>
	<atom:link href="http://weblogs.manas.com.ar/spalladino/category/ruby/rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://weblogs.manas.com.ar/spalladino</link>
	<description>Another spot on the blogosphere</description>
	<lastBuildDate>Tue, 31 Jan 2012 14:38:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>How to check if object can be destroyed if it has dependent: restrict associations</title>
		<link>http://weblogs.manas.com.ar/spalladino/2012/01/31/how-to-check-if-object-can-be-destroyed-if-it-has-dependent-destroy-associations/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2012/01/31/how-to-check-if-object-can-be-destroyed-if-it-has-dependent-destroy-associations/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 14:35:14 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=350</guid>
		<description><![CDATA[Rails provides several handy options for specifying how to deal with associated models upon deletion, for example: class Blog has_many :posts, :dependent =&#62; :destroy end The destroy value for the dependent option will call the destroy method for every post in the blog when the blog itself is destroyed. Other options are delete or nullify, [...]]]></description>
			<content:encoded><![CDATA[<p>Rails provides <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many-label-Options">several handy options</a> for specifying how to deal with associated models upon deletion, for example:</p>
<pre>
class Blog
  has_many :posts, :dependent =&gt; :destroy
end
</pre>
<p>The <em>destroy</em> value for the <em>dependent</em> option will call the destroy method for every post in the blog when the blog itself is destroyed. Other options are delete or nullify, but the one we are interested in is <strong>restrict</strong>.</p>
<p>By specifying a relation as dependent restrict, Rails will prevent us from destroying a particular object if it has any associated objects. In the example, we would not be able to destroy a Blog if it has any Posts. It is implemented simply, by raising an <a href="http://apidock.com/rails/ActiveRecord/DeleteRestrictionError">ActiveRecord::DeleteRestrictionError</a> if there is any associated object.</p>
<p>Now, this works perfectly for preventing us from accidentally destroying an object, but we will usually want to check if we can destroy it beforehand, this is, when rendering a page to the client with a big bad <em>delete</em> button. Showing a delete button only to show an alert box with a "Could not delete" annoying message is certainly not a good practice, we should simply not draw the delete button in the first place.</p>
<p>How do we check this? We could manually check if each and every one of the associations we have marked with dependent restrict in the object are empty, but taking Rails DRY principle into account, we would like to automatically get that information from the object.</p>
<p>Luckily, ActiveRecord provides <a href="http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html">reflection methods</a> for obtaining info on the associations. Therefore, given an object, we can iterate its associations, and check if the restricted ones are empty or not.</p>
<p>This all boils down to <a href="https://gist.github.com/1710839">this small method</a>, which can be placed as an initializer in the Rails app:</p>
<pre>
class ActiveRecord::Base
  def can_destroy?
    self.class.reflect_on_all_associations.all? do |assoc|
      assoc.options[:dependent] != :restrict ||
        (assoc.macro == :has_one &amp;&amp; self.send(assoc.name).nil?) ||
        (assoc.macro == :has_many &amp;&amp; self.send(assoc.name).empty?)
    end
  end
end
</pre>
<p>That's it! Now you can simply make a small helper method that renders a destroy link if can_destroy?, or a plain span notifying the user why she cannot destroy the object.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2012/01/31/how-to-check-if-object-can-be-destroyed-if-it-has-dependent-destroy-associations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Default request parameters in Rails functional tests</title>
		<link>http://weblogs.manas.com.ar/spalladino/2011/12/02/default-request-parameters-in-rails-functional-tests/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2011/12/02/default-request-parameters-in-rails-functional-tests/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 16:01:46 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=343</guid>
		<description><![CDATA[I was looking for an easy way to force every request in a functional test in Rails to use a set of parameters by default, regardless of being specified explicitly. This is, every time I write: it "should get index" do get :index end Rails should actually do: it "should get index" do get :index, [...]]]></description>
			<content:encoded><![CDATA[<p>I was looking for an easy way to force every request in a functional test in Rails to use a set of parameters by default, regardless of being specified explicitly. This is, every time I write:</p>
<pre>
it "should get index" do
  get :index
end
</pre>
<p>Rails should actually do:</p>
<pre>
it "should get index" do
  get :index, :foo =&gt; 'value'
end
</pre>
<p>Lacking any option in the testing framework, I opted for simply monkeypatching the <b>process</b> method in <a href="http://api.rubyonrails.org/classes/ActionController/TestCase/Behavior.html">ActionController::TestCase::Behaviour</a>. This method is invoked whenever methods <b>get</b>, <b>post</b>, <b>put</b>, <b>delete</b> or <b>head</b> are called, so it is the easiest single point to modify.</p>
<p><a href="https://gist.github.com/1423757">This gist</a> has the necessary code to perform the patch. If you are using <a href="https://www.relishapp.com/rspec">rspec</a>, simply copy the file in the spec/support folder.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2011/12/02/default-request-parameters-in-rails-functional-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deleting children with accepts_nested_attributes_for in Rails</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 19:23:51 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=180</guid>
		<description><![CDATA[On the previous post I wrote a few lines on the basic usage of the accepts_nested_attributes_for method in rails models. I strongly recommend reading that post before this one if you haven’t. Although there is a standard way for deleting items, there is few information on how to deal with them on the model or [...]]]></description>
			<content:encoded><![CDATA[<p>On the <a href="http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/">previous post</a> I wrote a few lines on the basic usage of the <font face="courier new">accepts_nested_attributes_for</font> method in rails models. I strongly recommend reading that post before this one if you haven’t.</p>
<p>Although there is a standard way for deleting items, there is few information on how to deal with them on the model or the controllers without messing with the unprocessed parameters. I’ll try to go over some of the different ways for deleting (or rejecting) children.</p>
<h3>Do not create at all</h3>
<p>Before actually deleting, it is important to consider the case in which you do not want to create the child in the first place. Doing this is easy and handled completely on the model: there is a very useful <font face="courier new">reject_if</font> option that allows you to specify conditions under which you do not want to process a specific child. </p>
<div class="csharpcode-wrapper">
<pre>accepts_nested_attributes_for :children
  :reject_if =<span class="str">&gt;</span> proc { |att| att['name']<span class="cls">.blank</span>? }</pre>
</div>
<p>The procedure runs for every child, if it evaluates to true, that set of parameters is ignored. Note that this is not the same as a validation: the child will be ignored simply rejected, and will not raise a validation error (children validation and parental control will be left for another post).</p>
<p>Remember that here you must predicate on the raw attributes. The class is not constructed (unless you manually do it in the procedure) so you do not have access to any model fields or instance methods.</p>
<p>This method is useful when you display a text field for the user to complete, which represents the child. If the user does not want to fill that field (<em>name</em> in the example), the child will not be created. </p>
<p>Suppose you have 5 empty text fields for the user to fill his/her hobbies. Should a user have only 3 hobbies, then you want to create only 3 instances of the Hobby class that belong_to that user.</p>
<h3>Check _delete</h3>
<p>The recommended option for deleting an item is setting a _delete parameter to true in the attributes. This is, if you have a set of parameters like the following:</p>
<div class="csharpcode-wrapper">
<pre>children_attributes =<span class="str">&gt;</span>
    1 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 16, :name =<span class="str">&gt;</span> Jack, :_delete =<span class="str">&gt;</span> true }
    2 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 18, :name =<span class="str">&gt;</span> Mary }</pre>
</div>
<p>Then Jack will be removed from the association to his parent. If the association has <font face="Courier New">:dependent =&gt; :destroy</font> set, Jack will be completely destroyed.</p>
<p>It is critical not to forget adding the allow_destroy option to the nested attributes method:</p>
<div class="csharpcode-wrapper">
<pre>accepts_nested_attributes_for :children,
  :reject_if =<span class="str">&gt;</span> proc { |att| att['name']<span class="cls">.blank</span>? },
  :allow_destroy =<span class="str">&gt;</span> true</pre>
</div>
<p>The rationale behind this feature is that if the user wants to delete an item, he/she must simply check a box named <font face="Courier New">_delete</font> and the controller will forward the parameter to the model, which will remove the child.</p>
<p>If you want to use a different method for deleting (in the hobbies example, delete when the user clears the textbox) you can use javascript to toggle a hidden checkbox whenever a textbox changes, for example. But this is clearly delegating model logic to the view, so a different approach is needed.</p>
<h3>Let the controller do it</h3>
<p>Since we are messing with the raw params representation of the object, the controller could simply iterate over each of the <font face="courier new">children_attributes</font> and add a <font face="courier new">_delete</font> parameter whenever needed, if a certain condition occurs.</p>
</p>
<p>However, if we had rejected the previous javascript-based solution for deleting a child since it implies keeping model logic in the view, why should we be happy by moving it to the controller? We have to move another step further.</p>
<h3>Mark for destruction</h3>
<p>No, we will not hack the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002347">attributes=</a> method to manually walk the <font face="courier new">children_attributes</font> params and add the deletion flag. Since we are in the model, we will use the objects themselves.</p>
<p>The AutosaveAssociation class has a handy method for <a href="http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html#M002196">marking objects for removal</a> which allows you to flag certain objects that should be destroyed when the parent is saved.</p>
<p>Therefore, you can add a callback before the parent is saved that walks through the children and marks for removal those who match a certain condition. And this time, you have the actual children, not some raw-params representation:</p>
<div class="csharpcode-wrapper">
<pre>before_save :mark_children_for_removal

def mark_children_for_removal
  children<span class="cls">.each</span> do |child|
    child<span class="cls">.mark_for_destruction</span> if child<span class="cls">.name</span><span class="cls">.blank</span>?
  end
end</pre>
</div>
<p>This allows you to keep all your model logic in your model, where it belongs, and avoid messing with nested parameters in the view or the controller.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Handling children with accepts_nested_attributes_for in Rails</title>
		<link>http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/</link>
		<comments>http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 19:44:45 +0000</pubDate>
		<dc:creator>spalladino</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://weblogs.manas.com.ar/spalladino/?p=174</guid>
		<description><![CDATA[Rails makes it easy to build HTML forms associated to a certain model. Simply using the form_for instruction on the view, writing a simple update method in the controller and setting validation logic on the model, makes standard CRUD operations incredibly easy to code. Since version 2.3, Rails also provides a convenient way of dealing [...]]]></description>
			<content:encoded><![CDATA[<p>Rails makes it easy to build HTML forms associated to a certain model. Simply using the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001604">form_for</a> instruction on the view, writing a simple update method in the controller and setting validation logic on the model, makes standard CRUD operations incredibly easy to code.</p>
<p>Since version 2.3, Rails also provides a convenient way of dealing with multi-model forms, specifically parent-children relations. Ryan has an <a href="http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes">excellent blog post</a> on the subject, I strongly recommend taking a look at it before going on reading if you have never used <a href="http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#M002132">accepts_nested_attributes_for</a> or <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605">fields_for</a>.</p>
<p>To make a long story short, the accepts_nested_attributes_for method applied to a model allows you to <strong>assign values directly to the children</strong>, using the same hash format as for standard attributes.</p>
<h3>An example</h3>
<p>For example, having a Parent class which <font face="courier new">has_many children</font> of class Child, a typical POST with data for both classes would look like the following:</p>
<div class="csharpcode-wrapper">
<pre>params =<span class="str">&gt;</span>
    action =<span class="str">&gt;</span> update
    id =<span class="str">&gt;</span> 1
    controller =<span class="str">&gt;</span> parents
    parent =<span class="str">&gt;</span>
        first_name =<span class="str">&gt;</span> John
        last_name =<span class="str">&gt;</span> Doe
        age =<span class="str">&gt;</span> 40
        children_attributes =<span class="str">&gt;</span>
            1 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 16, :name =<span class="str">&gt;</span> Jack }
            2 =<span class="str">&gt;</span> { id =<span class="str">&gt;</span> 18, :name =<span class="str">&gt;</span> Mary }</pre>
</div>
<p>(I removed several symbols from the hash to improve readability)</p>
<p>Note the <font face="Courier new">children_attributes</font> element among the parent’s attributes. The fields_for command produces the necessary syntax to produce POST data that will be converted to a hash in the convenient way for accepts_nested_attributes_for to interpret.</p>
<p>The <font face="courier new">children_attributes</font> is not an array but a hash, and its keys are a simple indexer, not the IDs of the model, which is used to group attributes from a single child entity toghether. </p>
<p>The reason for not using IDs is simple once you think about it: the model being edited might not be saved by the time it is sent to the client (therefore its id is nil), so it is a good practice to keep a hidden field with the id for each of the children being displayed.</p>
<h3>On the view</h3>
<p>Taking a look at the page source generated, we can see the naming convention rails uses to generate a hash with the previous structure:</p>
<div class="csharpcode-wrapper">
<pre>parent[children_attributes][0][name]</pre>
</div>
<p>This naming is automatically generated by opening a new context using the fields_for instruction in the view.</p>
<h3>On the model</h3>
<p>The change in the model is really simple, as it involves simply telling Rails which classes might be updated directly from the parent:</p>
<div class="csharpcode-wrapper">
<pre>accepts_nested_attributes_for :children</pre>
</div>
<p>We will look into additional options (rejecting and deleting) later.</p>
<h3>On the controller</h3>
<p>Note that all these changes only involve the view (clearly) and a single line in the model to specify which classes may be modified through the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002347">attributes</a> accessor. <strong>The controller remains as dumb as before:</strong></p>
<div class="csharpcode-wrapper">
<pre>def update
    if @parent<span class="cls">.update_attributes</span> params[:parent]
        redirect_to :action =<span class="str">&gt;</span> 'success_page'
    else
        render :action =<span class="str">&gt;</span> 'edit'
    end
end</pre>
</div>
<p>Not even a single mention to the children, the method is untouched.</p>
<h3>After that…</h3>
<p>Once you start dealing with certain validations and callbacks, keeping in mind when are these children validated created, updated and deleted is extemely important. Deleting items is specially delicate here, and will make a good subject for the next post!</p>
]]></content:encoded>
			<wfw:commentRss>http://weblogs.manas.com.ar/spalladino/2010/03/03/handling-children-with-accepts_nested_attributes_for-in-rails/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

