Question

I'm creating a small blog app to learn Rails - users can login, create posts and comment on other users posts. Right now i'm adding Ajax to the 'add your comment' page and got some design problems on the way. The page flow looks like this:

# post section
 :post.title here
 :post.username here
 :post.created_at here
 :post.body here

# comments section (sorted by date of creation):
:number of comments here

:first comment
:second comment
...
:last comment

# add comment section
:text_area here
:submit button here

The problems:

1 - The comments are sorted by date of creation, so my ajax call adds the new comment to the top of the page. If i change the sort behaviour, the ajax code is broke.

2 - A comment div can have 3 css classes: .odd, .even or .admin (apply cycle odd/even or admin if the comment is made by a admin user). Right now i'm hard coding these class names and using some if's to get the right one. This is bad too, if a change the css class names, the ajax code is broke.

How can i avoid these things, or at least improve? Here's my create.js.erb:

var div = $('#comments_div');
var comment_class = div.children().first().attr('class')
var new_class;

<% if current_user.admin == 1 %>
    new_class = 'comment_body_admin'
<% else %>
if (comment_class === 'comment_body_odd')
    new_class = 'comment_body_even'
else
    new_class = 'comment_body_odd'
<% end %>

var new_div = $('#comments_div').prepend("<%= j render @comment %>");
new_div.children().first().attr('class', new_class)

Thanks for any help!

Était-ce utile?

La solution

1 - How would you change the comment sort other than reversing the created at order? In that case you need to make create.js.erb aware of the sort order and use append instead of prepend.

2 - Apply the 'admin' class for admins, but leave the even-odd striping to CSS. Something like this ought to do it:

.comment:nth-child(2n) { background: #eeeeee; }

Also it is more efficient to build your node and manipulate its attribute before you insert it into the DOM :

var comment = $("<%= j render @comment %>").addClass('comment')
comment.addClass(new_class)
$('#comments_div').prepend(comment)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top