【发布时间】:2014-12-09 19:28:28
【问题描述】:
我有一个模型“事物”,它有_许多“评论”。我希望@thing.cmets 列表在按下“发表评论”按钮时使用 ajax 刷新。
此代码用于列出第一条评论的文本:
查看
<script type="text/javascript">
$("#post").click(function () {
$.get( "<%= postcomment_thing_path(:id => @thing.id) %>", function( data ) {
$('#comments_h2').html(data);
});
});
</script>
控制者:
def postcomment
@thing = Thing.find(params[:id])
render text: @thing.comments.first.text.to_s
end
但是当我尝试打印整个注释块时,它只打印一个“#”。
控制者:
def postcomment
@thing = Thing.find(params[:id])
render text:
@thing.comments.each do |comment|
comment.text.to_s
end
end
如何打印所有 cmets 的文本?
【问题讨论】:
-
尝试将 each 替换为 map 并使用连接来组合结果。
@thing.comments.map { |comment| comment.text.to_s }.joins("<br>") -
它返回“未定义的局部变量或方法“注释””,你确定这是正确的语法吗?
-
是的。但我确实有一个错误@thing.cmets.map { |comment| comment.text.to_s }.join("
")。应该是加入,而不是加入。另一件事,我会使用 render_to_string 而不是 render :text,但这是一个偏好问题。 -
你知道它为什么会返回那个错误吗?
标签: ruby-on-rails ruby ajax ruby-on-rails-4 controller