【问题标题】:how to render a collection in rails using jquery and partials如何使用 jquery 和 partials 在 Rails 中呈现集合
【发布时间】:2012-05-04 08:58:11
【问题描述】:

我正在尝试在 Rails 3.1 上呈现 cmets 集合,但网页上仅显示该集合的第一条评论(cmets 与想法相关联)。

首先,cmets-controller:

def index
  @comments = Comment.find_by_thought_id(params[:thought_id])
  respond_to do |format|
    format.html
    format.js
  end
end

然后,视图 index.js.erb

$("#thought_<%= params[:thought_id] %>").append("<%= escape_javascript(render'index') %>").effect("highlight", {}, 3000);

我正在渲染索引,所以现在到 _index.html.erb

<div id="comments_<%= params[:thought_id] %>">
  <%= render @comments %>
</div>

最后是 _comment.html.erb

<%= div_for comment do %>
  Posted <%=time_ago_in_words(comment.created_at)%> ago<br />
  <%= link_to 'Delete', comment_path(comment), :method => :delete, :class => "delete", :remote => true  %>
  <%= content_tag(:p, comment.description, :class => "comment-body") %>
<% end %>

为什么 Rails 只给我一条评论?

提前致谢

【问题讨论】:

    标签: jquery ruby-on-rails collections partial-views render


    【解决方案1】:
    1.9.3-head :035 > Tag.find_by_name('ruby')
      Tag Load (0.3ms)  SELECT "tags".* FROM "tags" WHERE "tags"."name" = 'ruby' LIMIT 1
     => #<Tag id: 1231, name: "ruby", created_at: "2012-04-23 10:25:07", updated_at: "2012-04-23 10:25:07"> 
    1.9.3-head :036 > Tag.where(:name => 'ruby')
      Tag Load (1.4ms)  SELECT "tags".* FROM "tags" WHERE "tags"."name" = 'ruby'
     => [#<Tag id: 1231, name: "ruby", created_at: "2012-04-23 10:25:07", updated_at: "2012-04-23 10:25:07">, #<Tag id: 2420, name: "ruby", created_at: "2012-04-23 18:21:35", updated_at: "2012-04-23 18:21:35">]
    

    当您使用 find_by_name 之类的动态查找器时,请注意此 LIMIT 1。

    你最好使用where,它更快,因为它不是动态方法。

    【讨论】:

      【解决方案2】:

      代替:

      Comment.find_by_thought_id
      

      尝试:

      Comment.find_all_by_thought_id
      

      【讨论】:

      • 也许这会教你使用Comment.where(thought_id: params[:thought_id])而不是hard_to_read_and_maintain动态查找器:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多