1
Rails 5.2
datatables

I am following a mini tutorial, on implementing databables with Rails. The table

 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

What I really want to display for the column user, is the user email, but the user email is in the table Users. How do I implement this with datatables, and stil be able to do sorting, based on the email, not the user_id that's in the blogs table?

EastsideDev
  • 6,257
  • 9
  • 59
  • 116

1 Answers1

1

Try this method:

Assuming you have the routes set to resources: blogs

Your table in the index.html.erb will be

<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>

Add _blog.json.jbuilder in blogs

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

Add index.json.jbuilder in blogs

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

This will create the datatable using json object by taking the @blogs instance variable from your index action

and for your question how to show email in the user column which is in the user table, Assuming you have referenced the user table with blogs table, ie

in your blogs model you should have an association:

belongs_to :user

now you wil get the user email by blog.user.email

Abhishek Aravindan
  • 1,432
  • 6
  • 23