Forum: Ruby on Rails Noob question... confused

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.
Eric B. (Guest)
on 2006-05-03 21:08
(Received via mailing list)
If I have several controller actions which have this same line of code
(or
more), how can I DRY up the line without running into complaints about
redirecting or rendering only once?  If I put the line in another method
in
my controller, won't it think I'm redirecting?

I want to dry up lines like this:  @listing = Listing.find(params[:id])

 def customerview
       @listing = Listing.find(params[:id])
       render :action => 'edit'
  end

  def view
       @listing = Listing.find(params[:id])
       render :action => 'edit'
  end

  def edit
       @listing = Listing.find(params[:id])
       render :action => 'edit'
  end

Thanks,

Eric
Stephen B. (Guest)
on 2006-05-03 21:08
(Received via mailing list)
You can add non-routable methods into controllers by making the method
private:

def customerview
   find_listing
   # .. rest of code
end

def view
   find_listing
   # .. rest of code
end

private
def edit_listing
   @listing = Listing.find(params[:id])
   render :action => 'edit'
end

Steve
Stephen B. (Guest)
on 2006-05-03 21:08
(Received via mailing list)
This isn't quite right actually.  Should be:

def customerview
   # .. any other code
   find_listing
end

def view
   # .. any other code
   find_listing
end

private
def edit_listing
   @listing = Listing.find(params[:id])
   render :action => 'edit'
end

That's if you're rendering the output in the edit_listing method.

Steve
Philip R. (Guest)
on 2006-05-03 21:08
(Received via mailing list)
Eric B. wrote:
> If I have several controller actions which have this same line of code
> (or more), how can I DRY up the line without running into complaints
> about redirecting or rendering only once?  If I put the line in another
> method in my controller, won't it think I'm redirecting?
>
> I want to dry up lines like this:  @listing = Listing.find(params[:id])

You could use a before_filter:

class MyController < ApplicationController
   before_filter :find_listing

   def customerview
     render :action => 'edit'
   end

   def view
     render :action => 'edit'
   end

   def edit
   end

   private
     def find_listing
       @listing = Listing.find(params[:id])
     end
end

--
Philip R.
http://tzinfo.rubyforge.org/ -- DST-aware timezone library for Ruby
This topic is locked and can not be replied to.