【问题标题】:Adding sortable column from another tables in datatables从数据表中的另一个表添加可排序列
【发布时间】:2020-02-23 15:11:14
【问题描述】:
Rails 5.2
datatables

我正在关注一个关于使用 Rails 实现数据表的迷你教程。表

 class BlogDatatable < AjaxDatatablesRails::ActiveRecord

  def view_columns
    @view_columns ||= {
      id:          { source: "Blog.id" },
      user:        { source: "Blog.user_id"}
      title:       { source: "Blog.title" },
    }
  end

  def data
    records.map do |record|
      {
          id:          record.id,
          title:       record.title,
          DT_RowId:    record.id,
      }
    end
  end

  def get_raw_records
    Blog.all
  end

end

我真正想为用户列显示的是用户电子邮件,但用户电子邮件在用户表中。如何使用数据表实现这一点,并且仍然能够根据电子邮件而不是 blogs 表中的 user_id 进行排序?

【问题讨论】:

  • 在 Rails 中使用 json 和 jbuilder 实现 Datatable 有更好的选择
  • @AbhishekAravindan 你能扩展一下吗?
  • 我假设你需要一个关于博客的数据表,并且你需要它在博客索引页面上......是吗??
  • 是的,这将用于索引视图
  • 你安装了吗gem 'jquery-datatables' ??

标签: ruby-on-rails datatables jquery-datatables-rails


【解决方案1】:

试试这个方法:

假设您将路由设置为resources: blogs

您在index.html.erb 中的表将是

<table class="responsive nowrap table table-hover" id="dttb-blogs" data-sort="true" data-source="<%= url_for(format: :json)%>">
 <thead>
  <tr>
   <th data-data="title">Title</th>
   <th data-data="user_email">User</th>
   <th data-data="url" data-orderable="false" data-class-name="all" data-searchable="false" class="skip-export" width="100px"></th>
  </tr>
 </thead>
</table>

在博客中添加_blog.json.jbuilder

json.extract! blog, :id, :title, :user_id, :created_at, :updated_at
json.user_email blog.user.email
json.url blog_url(blog, format: :json)

在博客中添加index.json.jbuilder

json.set! :data do
json.array! @blogs do |blog|
json.partial! 'blogs/blog', blog: blog
json.url  "
          #{link_to 'Show', blog }
          #{link_to 'Edit', edit_blog_path(blog)}
          #{link_to 'Destroy', blog, method: :delete, data: { confirm: 'Are you sure?' }}
          "
end
end

这将使用 json 对象创建数据表,方法是从您的索引操作中获取 @blogs 实例变量

对于您的问题,如何在用户表中的用户列中显示电子邮件,假设您已经使用 blogs 表引用了用户表, 即

在您的博客模型中 你应该有一个关联:

belongs_to :user

现在您将通过blog.user.email 收到用户电子邮件

【讨论】:

  • 当我能做到的时候,我为什么要做这一切:从控制器方法渲染 json: { data: @blogdata }
猜你喜欢
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 2022-12-22
  • 2016-09-22
  • 1970-01-01
相关资源
最近更新 更多