Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Polymorphic partials #273

Closed
netwire88 opened this issue Jun 26, 2012 · 2 comments
Closed

Polymorphic partials #273

netwire88 opened this issue Jun 26, 2012 · 2 comments
Labels

Comments

@netwire88
Copy link

I have a data model where a User can like a Project, Suggestion, Comment, or other objects.
The models are set up correctly, and likes/show.rabl works if we were just to support the Project child

object @like
attributes :id, :created_at, :target_type, :target_id, :user_id
child :user => :user do
  extends "users/show"
end
child :target do
  node do |project|
    partial('projects/show', :object => project)
  end
end

However, I want to be able to use partials of suggestions/show, comments/show as well depending on target_type.

I tried this but it's not working:

child :target do |u|
  u.target.map do |r|
    if r.is_a?(Suggestion)
      partial("suggestions/show", :object => r)
    elsif r.is_a?(Project)
      partial("projects/show", :object => r)
    end
  end
end

I get undefined method target for <Rabl::Engine:0x69fb988>. However, I don't get this error in the first case. Any ideas?

@databyte
Copy link
Collaborator

So child doesn't work with blocks the same way node does. Node calls the block explicitly to merge in the return whereas child traverses the object namespace.

object @foo         # root_object is @foo

child :target do    # root_object is now @foo.target
  attribute :bar    # comes from @foo.target.bar
end

node :hello do |hi| # root_object is still @foo
  hi.bar            # comes from @foo.bar
end

What you probably want is to leave your child the way it was but within node, do your if/else checks.

child :target do
  node do |project|
    if project.is_a?(Suggestion)
      partial("suggestions/show", :object => project)
    elsif project.is_a?(Project)
      partial("projects/show", :object => project)
    end
  end
end

(or something like that)

@netwire88
Copy link
Author

Thank you databyte, that worked very well.

This is what I ended up using:

child :target do
  node do |r|
    if r.is_a?(Suggestion)
      partial("suggestions/show", :object => r)
    elsif r.is_a?(Project)
      partial("projects/show", :object => r)
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants