# Restful polymorphic

**URL:** <https://www.ruby-forum.com/t/restful-polymorphic/81787>\
**Category:** Rails\
**Created:** [January 14, 2007, 9:17am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787 "2007-01-14T09:17:34Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 14, 2007, 9:17am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/1 "2007-01-14T09:17:34Z")

</div>

In working on a RESTful website, I’ve encountered a stumbling block  
involving polymorphic associations.

For example, given:

map.resources :posts do |post|  
post.resources :comments, :name\_prefix =\> ‘post\_’  
end  
map.resources :photos do |photo|  
photo.resources :comments, :name\_prefix =\> ‘photo\_’  
end

Where comments is polymorphic. The acts\_as\_commentable plugin fits the  
bill.

So we have routes like:

/posts/678/comments  
/photos/185/comments

If we want to create a new comment for photo 678 we would send a POST to  
/posts/678/comments. Nice and RESTful.

But… how do I generate the path for the form target if the comment  
form is in a shared partial (DRY)?

I did find one post about this on Rails Weenie and the answer was more  
of a workaround… an ugly helper that uses link\_to. Is there any way to  
do this gracefully, such as \*\_path?

Ideally:

\<% form\_for(comment\_path(@photo)) %\>

…would be smart enough to determine the object type of @photo and  
generate the correct /photos/@photo.id/comments route automatically.

Any thoughts? Anyone run into this, and if so how did you solve it?

Thanks!

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 16, 2007, 7:21pm UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/2 "2007-01-16T19:21:40Z")

</div>

Funny, moments before you posted this I was struggling with the exact  
same thing _and_ was looking at the exact same Techno Weenie article.

I opted to go with a modified version of the before\_filter approach like  
so. Read below for my observations.

# POST /comments

# POST /comments.xml

def create  
@comment = Comment.new(params[:comment])

```
@commentable = find_commentable
@commentable.comments << @comment

respond_to do |format|
  if @comment.save
    flash[:notice] = 'Comment was successfully created.'
    format.html { eval("redirect_to 

```

#{@commentable.class.to\_s.underscore}\_url(@commentable)") }  
format.js # render create.rjs; update comment listing  
format.xml { head :created, :location =\>  
eval("#{@commentable.class.to\_s.underscore}\_url(@commentable)") }  
else  
format.html { render :controller =\>  
@commentable.class.to\_s.underscore, :id =\> @commentable.id, :action =\>  
:show }  
format.js { :render :js =\> @comment.errors.to\_json } # XXX  
format.xml { render :xml =\> @comment.errors.to\_xml }  
end  
end  
end

private

def find\_commentable  
# lazy regex, just finds instances of /controller/id  
sections = request.env[‘REQUEST\_URI’].scan(%r{/(\w+)/(\d\*)})

```
sections.map! do |controller_name, id|
  [controller_name.singularize.camelize, id]
end

klass, id = sections.pop
eval("#{klass}.find(id)")

```

end

I’ve got the entire thing working brilliantly as long as it’s a Ajaxed  
or if the non-Ajax submission is valid. What I haven’t figured out yet  
to do properly is handle invalid non-Ajax submissions and still populate  
the input fields.

I see two possible paths:

1. Perform a redirection after doing some session storage. Implement a  
before\_filter that checks for session-stored form submissions and  
errors.

2. Move all views that are commentable into partials.

Though #2 is “kinda OK”, it remains a bit of a stretch.  
Interested to hear your thoughts and any code improvements.

- Roderick

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 16, 2007, 10:24pm UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/3 "2007-01-16T22:24:56Z")

</div>

I’m glad I’m not the only one struggling with this problem! Frankly, I’m  
a bit surprised Rails 1.2 is going to be released with open questions  
like this.

How are you generating your form destinations in your comment form(s)?

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 16, 2007, 11:18pm UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/4 "2007-01-16T23:18:15Z")

</div>

Carl J. wrote:

> How are you generating your form destinations in your comment form(s)?

Here’s what I have, let me know if you work up something better.

In news\_items/show.rhtml:

\<%= render :partial =\> ‘shared/comment\_form’, :locals =\> {  
:commentable =\> @news\_item } %\>

shared/\_comment\_form.rhtml:

## New comment

```
<%= error_messages_for :comment %>

<% remote_form_for(:comment, :url => comments_path(commentable)) do 

```

|f| -%\>

Comment  
  
\<%= f.text\_area :body %\>

```
  <p>
    <%= submit_tag 'Create' %>
  </p>
<% end -%>

```

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 16, 2007, 11:38pm UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/5 "2007-01-16T23:38:45Z")

</div>

> ```
> <% remote_form_for(:comment, :url => comments_path(commentable)) do 
> 
> ```
> 
> |f| -%\>

I am not able to simply use comments\_path because I have overlapping  
routes. Like this:

map.resources :pictures do |picture|  
picture.resources :comments, :name\_prefix =\> ‘picture\_’

map.resources :posts do |post|  
post.resources :comments, :name\_prefix =\> ‘post\_’

So in order for my New Comment form to POST to the correct URL I have to  
use either picture\_comments\_path or post\_comments\_path. In the routing  
above the name\_prefixes are required, otherwise one overwrites the  
other.

It seems like your solution will work for you as long as you have only  
one parent defined in the routing for comments, but as soon as you want  
to add comments for something like :blog\_items, comments\_path is not  
going to know what to do. Unless I’m missing something?

Carl

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 17, 2007, 12:43am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/6 "2007-01-17T00:43:33Z")

</div>

> You are right. I hadn’t tackled that issue yet. However, it should be  
> solvable by something (untested and hand-coded) like:
> 
> pictures/show.rhtml:
> 
> \<%= render :partial =\> ‘shared/comment\_form’, :locals =\> {  
> :commentable =\> @picture, :name\_prefix =\> ‘picture\_’ } %\>

Yeah that’s pretty simple. I’ll probably do the same too… been putting  
off converting my comment submission to RESTful so far.

I still think that the \_path generators should be able to do a little  
magic and determine the correct route for polymorphic targets. Hopefully  
that will eventually be built-in. I will try to tackle it myself in the  
Rails code but it will take me quite a while, if ever! 🙂

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 17, 2007, 12:19am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/7 "2007-01-17T00:19:54Z")

</div>

Carl J. wrote:

> It seems like your solution will work for you as long as you have only  
> one parent defined in the routing for comments, but as soon as you want  
> to add comments for something like :blog\_items, comments\_path is not  
> going to know what to do. Unless I’m missing something?

You are right. I hadn’t tackled that issue yet. However, it should be  
solvable by something (untested and hand-coded) like:

pictures/show.rhtml:

\<%= render :partial =\> ‘shared/comment\_form’, :locals =\> {  
:commentable =\> @picture, :name\_prefix =\> ‘picture\_’ } %\>

shared/\_comment\_form.rhtml:

\<% eval(“remote\_form\_for(:comment, :url =\>  
#{name\_prefix}comments\_path(commentable))”) do  
|f| -%\>

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 17, 2007, 8:47am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/8 "2007-01-17T08:47:38Z")

</div>

Roderick van Domburg wrote:

> You are right. I hadn’t tackled that issue yet. However, it should be  
> solvable by something (untested and hand-coded) like:
> 
> pictures/show.rhtml:
> 
> \<%= render :partial =\> ‘shared/comment\_form’, :locals =\> {  
> :commentable =\> @picture, :name\_prefix =\> ‘picture\_’ } %\>
> 
> shared/\_comment\_form.rhtml:
> 
> \<% eval(“remote\_form\_for(:comment, :url =\>  
> #{name\_prefix}comments\_path(commentable))”) do  
> |f| -%\>

FYI, this inspired me to convert to RESTful comment submissions and  
here’s what I did. I tried to limit what I pass to each partial since I  
already have to pass a bunch of pagination stuff.

show.rhtml:

\<%= render(:partial =\> ‘shared/comments’, :locals =\> {:comment\_pages =\>  
@comment\_pages, :count =\> @comment\_count, :item =\> @picture})%\>

shared/\_comments.rhtml:

\<% form\_for(:comment, :url =\>  
eval("#{item.class.to\_s.downcase}\_comments\_path(#{item.id})")) do |f| %\>

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [January 17, 2007, 11:09am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/9 "2007-01-17T11:09:41Z")

</div>

On 1/16/07, Carl J. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> \<% form\_for(:comment, :url =\>  
> eval(“#{item.class.to\_s.downcase}\_comments\_path(#{item.id})”)) do |f| %\>

We do a lot of polymorphic stuff like this where I work. Just a  
suggestion:

instead of  
eval(“#{item.class.to\_s.downcase}\_comments\_path(#{item.id})”)

try  
send(“#{item.class.to\_s.downcase}\_comments\_path”, item.id))

Or, wrap it up:  
def polymorphic\_comments\_path(item)  
send(“#{item.class.to\_s.underscore}\_comments\_path”, item))  
end

If you find yourself using eval, there’s usually another way to do it in  
Ruby.

–  
Chris W.

> **[err.the\_blog](http://errtheblog.com)**
>
> Err the Blog: Ruby and Rails from the front.

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [February 10, 2007, 5:05am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/10 "2007-02-10T05:05:48Z")

</div>

hi,  
so far, so good, I’m having the same problems.

say now I can create Comment for an Article, rendering comment form  
partial directly from /app/views/articles/show.rhtml

\<%= render(:partial =\> ‘shared/comment\_form’, :locals =\> {:item =\>  
@article, :name\_prefix =\> ‘article\_’})%\>

#/app/views/shared/\_comment\_form.rhtml  
\<%= error\_messages\_for :comment %\>

\<% form\_for(:comment, :url =\> polymorphic\_comments\_path(item)) do |f| %\>

Title  
Please be concise.\<%= f.text\_field 'title' %\>Comment  
Write your comment here.\<%= f.text\_area 'comment', :class =\> 'articleintroduction' %\>

\<%= submit\_tag "Create" %\>

\<% end %\>

this form will generate

which works well.

# routes.rb

map.resources :articles do |post|  
post.resources :comments, :name\_prefix =\> ‘article\_’  
end

all done.

# controller using simply\_commentable

# POST /comments

# POST /comments.xml

def create  
@commentable = find\_commentable  
@comment = @commentable.comment\_by!(current\_user,params[:comment] )  
respond\_to do |format|  
if @comment.save  
flash[:notice] = ‘Comment was successfully created.’  
format.html { eval(“redirect\_to  
#{@commentable.class.to\_s.underscore}\_url(@commentable)”) }  
format.js # render create.rjs; update comment listing  
format.xml { head :created, :location =\>  
eval("#{@commentable.class.to\_s.underscore}\_url(@commentable)") }  
else  
format.html { render :controller =\>  
@commentable.class.to\_s.underscore, :id =\> @commentable.id, :action =\>  
:show }  
format.js { render :js =\> @comment.errors.to\_json } # to check  
format.xml { render :xml =\> @comment.errors.to\_xml }  
end  
end  
end

private  
def find\_commentable  
sections = request.env[‘REQUEST\_URI’].scan(%r{/(\w+)/(\d\*)})  
sections.map! do |controller\_name, id|  
[controller\_name.singularize.camelize, id]  
end  
klass, id = sections.pop  
eval("#{klass}.find(id)")  
end

as suggested. I’m posting the entire thing just for reference to other  
users.  
anyway a question arises, say I want to edit a comment, we should use  
the controller Comments, how is the link\_to built? with which routes and  
params? what should we put in the views/partials?

thanks

---

<div class="post-metadata">

**Author:** ![cjnkns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/c5a1d2/32.png) [@cjnkns](https://www.ruby-forum.com/u/cjnkns)\
**Post date:** [February 16, 2007, 12:49am UTC](https://www.ruby-forum.com/t/restful-polymorphic/81787/11 "2007-02-16T00:49:56Z")

</div>

Have you made any progress on this? I’ve been searching for the same  
answers.

Claudio P. wrote:

> hi,  
> so far, so good, I’m having the same problems.
> 
> say now I can create Comment for an Article, rendering comment form  
> partial directly from /app/views/articles/show.rhtml
> 
> …snip…
> 
> as suggested. I’m posting the entire thing just for reference to other  
> users.  
> anyway a question arises, say I want to edit a comment, we should use  
> the controller Comments, how is the link\_to built? with which routes and  
> params? what should we put in the views/partials?
> 
> thanks
