Automatically Create Relations with Inherited Resources and/or Rails3 Magic

Angelegt von suung Tue, 25 Jan 2011 14:04:00 GMT

If you have a resource (in my case that's Document and want to add or create a related resource (in my case Style) and you use Inherited Resources, your controller may look like this:

class DocumentController < InheritedResources::Base

  respond_to :html, :pdf

end

There is nothing going on, because InheritedResources will do the job for you: providing 'automatically' scaffold functionality.

Okay, in most cases you will not want that, you want to add something.

In my case that is, as I mentioned, to add or create a related 'Style' in the create-action

To override the create action, you could

def create
  super do
    @style=Style.create(params[:style])
    ...
  end
end

- in general.

Inherited Resources skips the 'super' giving you \create!' which can take the block.

Anyway, to really add a new style to the @document (that is used by the magic), i would have to do something like this:

 

 

  def create

    if params[:style]

      @style = Style.create(params[:style])

      @document = Document.new(params[:document])

      @document.style_id = @style.id if @style

    end

    create!

  end
I think, that speeks for itself.
Two thing here are not necessary:
  1. params[:style] and the if condition (because inherited resources could already check that)
  2. @document = Document.new (because inherited resources already did that in fact

To get rid of it, we use a other trick:

 

class Document < ActiveRecord::Base

  belongs_to :style  

  accepts_nested_attributes_for(:style)

end

This will let the style-attribute take a Hash that can lead to a full create, which is nice.
It's an Rails3 Feature.

With IR again, you can

class DocumentsController &lt; InheritedResources::Base



    protected



    def begin_of_association_chain

      case

      when params[:style_id]

        Style.find(params[:style_id]).try(:documents)

      when params[:style]

        Style.create!(params[:style]).try(:documents)

      else

        Document

      end

    end

  end
Trackbacks

Verwenden Sie den folgenden Link zur Rückverlinkung von Ihrer eigenen Seite:
http://praktikanten.brueckenschlaeger.org/trackbacks?article_id=427

Leave a comment

Comments