views:

31

answers:

2

Hi,

I've created a custom method in my model, which finds a record by name:

def find_city
  Place.find_by_name(city_name)
end

I can call this method in my view with place_path(@place.find_city), which works great when a place with the appropriate name exists. What I would like to be able to do is write in a redirect for when the place doesn't exist, and I'm unsure about where the logic should go. Basically, I would like to write something like:

respond_to do |format|
  if @place.find_city.blank?
    format.html { redirect_to :action => "new" }
  else
    format.html { render :action => "show" }
  end
end

...but I would still like the controller to respond to place_path(@place) in the usual manner as well. Any help would be much appreciated!

EDIT: sorry for the confusion, should have explained my example further. I have a Place model that has both 'city_name' and 'name' as attributes. The find_city custom method that I detailed above finds the place whose name matches the city_name for another place eg.

Place.name = "foo"  
Place.city_name = "baz"

So therefore Place.find_city gives the record where Place.name = "baz". Cheers!

A: 

Hi Sonia

Do something like this

keep your model as

class City < ActiveRecord::Base

  named_scope :by_name, lambda {|city|{:conditions => "name=#{city}"}}

end

in your controller

class CitiesController < ApplicationController


  def index

    @city = City.by_name(<city name>)

    if @city.nil?

      <redirect to one place>

    else

      <redirect to another place>

    end

  end

end

and in your view access the @city parameter.

** Normally we shouldnt access Models directly from views. Either we should do it through controllers or helpers

Hope this helps

cheers

sameera

sameera207
Thanks for your response - I actually don't have a City model, sorry I should have explained my problem a bit better! I've added a clarification above. Sorry!
Sonia
HiIn that case you can replace City with Place and should work. cheerssameera
sameera207
A: 

I've decided to create a helper method for this problem - what I've described above might seem a bit of an unorthodox approach, but I only need the find_city method to create a links bar for each place, so I don't think I really need to create a separate city model, or define a formal self-referential relationship. Just in case anyone might find this useful, I've created a links_bar helper:

module PlacesHelper

  def links_bar(place)
    if place.city_name.blank?
       render "no_city_links"
    elsif place.find_city.nil?
      render "nil_find_city_links"
    else
      render "complete_links"
    end
  end

end

Each partial then has the required behaviour depending upon whether or not the find_city method returns a record or not.

Sonia