【问题标题】:Rails 4 - Update table by links from collection with AJAX UJSRails 4 - 通过使用 AJAX UJS 的集合中的链接更新表
【发布时间】:2014-09-06 17:37:02
【问题描述】:

我有一个收藏中的新闻列表。

上面是带有年份编号的分页列表,2010 -> 2014

点击每个将按当年排序新闻列表。

我想对其进行 AJAX 化,因此不会发生页面重新加载。

我错过了什么?

一个带有一些 UJS 的 index.js.erb 文件,但是应该怎么做呢?

提前致谢!

news_controller.rb:

@news_years = News.all.map { |news| news.date.year }.uniq.sort

if params[:year].present?
  @news = News.order("date DESC").by_year(params[:year].to_i).load
else
  @news = News.order("date DESC").by_year(DateTime.now.year).load
end

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @news }
  format.js
end

index.haml:

%ul.pagination
  - @news_years.each do |year|
    - if params[:year] == year.to_s
      %li.active
        %span.page
          = link_to year, news_index_path(:year => year.to_s), remote: true
    - else
      %li
        %span.page
          = link_to year, news_index_path(:year => year.to_s), remote: true

.panel-group#news-accordion
  - cache(cache_key_for_news) do
    - @news.each do |news|
      = render partial: 'news', locals: {news: news}

_news.haml:

- cache(news) do
  .panel.panel-default
    .panel-heading.panel-heading-custom
      .panel-title
        %a{:"data-toggle" => "collapse", :"data-parent" => "#news-accordion", :href => "#collapse-#{news.id}"}
          %i.fa.fa-plus.fa-1x
          %small= news.date.strftime('%d.%m.%y') unless news.date.blank?
          \-
          %small= news.title
          - if can? :manage, news
            = link_to t('.edit_news'), edit_news_path(news), class: 'btn btn-primary btn-xs', role: 'button'
            = link_to t('.delete_news'), news, :confirm => 'Er du sikker?', :method => :delete, class: 'btn btn-primary btn-xs', role: 'button'

     .panel-collapse.collapse{:id => "collapse-#{news.id}"}
       .panel-body
         = news.content.html_safe
         %br/

【问题讨论】:

    标签: jquery ruby-on-rails ajax ruby-on-rails-4 ujs


    【解决方案1】:

    index.js.erb 必须填充#news-accordion 块。它应该是这样的:

    $("#news-accordion").html("<%= escape_javascript(render 'all_news', news: @news) %>");
    

    和部分 _all_news.html.erb

    news.each do |news|
      = render partial: 'news', locals: {news: news}
    

    可选地,在 index.html 中我会渲染 _all_news.html.erb 而不是循环每个新闻。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      相关资源
      最近更新 更多