Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

better way to use link_to on rails 3


I need use this gem https://github.com/potatosalad/mongoid-data_table.

This is my model code:

class Admin
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Mongoid::DataTable
  #datatableblock
  ## data_table ##
  data_table_options.merge!({
    :fields => %w(id email created_at role actions),
    :searchable => %w(email role),
    :dataset => lambda do |admin|
      {
        0 => "<%= check_box_tag \"admin_ids[]\", admin._id, false, :class => \"check\" %>",
        1 => admin.id,
        2 => "<%= link_to(admin.email, admin_admin_path(admin._id)) %>",
        3 => admin.created_at,
        4 => admin.role,
        5 => "<%= link_to(I18n.t('admin.actions.show'), admin_admin_path(admin._id)) %> - <%= link_to(I18n.t('admin.actions.edit'), edit_admin_admin_path(admin._id)) %> - <%= link_to I18n.t('admin.actions.delete'), admin_admin_path(admin._id)%>",
        :DT_RowId => admin._id
      }
    end
  })
end

I know this action likely violating some principle of the Model-View-Controller architecture.

I need use link_to and ruby on rails code to generate correct content inside each columns.

Then my question is: How can I do it in a better way without violating the principles of MVC?

Thank you very much


Solution

  • That gem is a specialized use-case and may be suitable if you don't want to add another class or layer to your application, but it does violate MVC.

    The correct implementation (imo) of what that gem is trying to do is the Presenter Pattern.

    There are many gems for Rails which implement the same. Basically, this code should be in a custom class, and not in the model file.

    Watch this railscast by Ryan Bates to get a clear picture of how to do this without any gems and more importantly the addition of presenters in MVC.

    When you use presenters, decorators or other design patterns in tandem with MVC, they should not and do not typically violate the core architecture.