开发者

Custom method redirect in Rails

开发者 https://www.devze.com 2023-01-13 05:53 出处:网络
I\'ve created a custom method in my model, which finds a record by name: def find_city Place.find_by_name(city_name)

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!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消