devinross
devinross

Reputation: 2816

Ruby on rails: Render 2 partials or figure out the kind of class and object is

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

Upvotes: 1

Views: 610

Answers (3)

Andy Gaskell
Andy Gaskell

Reputation: 31761

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

Upvotes: 1

Kenny
Kenny

Reputation: 794

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.

Upvotes: 0

tliff
tliff

Reputation: 1764

try something like

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

Upvotes: 1

Related Questions