views:

168

answers:

3

I want to display different types of objects in the same ajax called controller function. I want to render out when I send back an ajax call. The problem is I want the "title" attribute of one object and the "name" attribute of another object. I can't render 2 partials and can seem to figure out how to check the type of object an object is. How do I solve this problem?

Here is my current controller setup (NOT CORRECT)

@objects =  Obj.find(:all,:conditions => ["name Like ?", "#{prefix}%"])
@moreObjects = ObjTwo.find(:all,:conditions => ["title Like ?","#{prefix}%"])

if @objects.empty?
  render :text => "No Matches"
else
  render :partial => 'one', :collection => @objects
end

if  @moreObjects.empty?
  render :text => "No Matches"
else
  render :partial => 'two', :collection => @moreObjects
end
+1  A: 

try something like

<%= obj.title if obj.respond_to?(:title) %>
tliff
A: 

You could use Object.is_a? but that's not a very clean solution. You could also try mapping your data before presentation to help keep your views lightweight.

Kenny
is_a? is at least in principal a bad practice in Ruby. Heard about duck typing?
Christoph Schiessl
Yeah, I completely agree. There are much better solutions. Just answering the question about object type checking posed above.
Kenny
+1  A: 

Here's one option that doesn't involve checking its type - in your Obj and ObjTwo classes add a new method:

def fancy_pants
  title
end

def fancy_pants
  name
end

Then you can combine @objects and @moreObjects - you'll only need one if statement and one partial.

@search_domination = @objects + @moreObjects

if @search_domination.empty?
  render :text => "No Matches"
else
  render :partial => 'one', :collection => @search_domination
end
Andy Gaskell
I was in the middle of writing up something almost exactly like this answer. Thus, +1.
Greg Campbell
Thanks Greg - Is there something you would have done differently? (besides wacky names) I'm always looking for new perspectives.
Andy Gaskell