1
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 进行排序?

4

1 回答 1

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

这将通过从索引操作中获取 @blogs 实例变量来使用 json 对象创建数据表

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

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

belongs_to :user

现在您将通过以下方式获得用户电子邮件blog.user.email

于 2019-10-29T03:51:01.353 回答