render layout inside other layout - DRY, Rails

Posted by chetan
on Saturday, October 27
put this code block inside your application_helper.rb

  def inside_layout(layout, &block)    
     layout = layout.include?('/') ? layout : "layouts/#{layout}"    
     @template.instance_variable_set("@content_for_layout", capture(&block))    
     concat(@template.render(:file => layout, :user_full_path => true), block.binding)    
   end
Now, use this method in layout, which you want to render in suppose 'application' layout

  <% inside_layout 'application' do %>
    your code
  <% end %>

How to add primary_key (mysql+rails) on table which already has content

Posted by chetan
on Monday, October 22
You have a legacy database in which one table doesn't have primary_key defined. Now, activerecord needs a primary_key to run queries on this table. What do we do?

Create a migration and execute following SQL query

   execute "ALTER TABLE table_name 
            DROP COLUMN to_be_primary_key, 
            ADD COLUMN to_be_primary_key BIGINT(20) AUTO_INCREMENT NOT NULL FIRST,
            ADD PRIMARY KEY(to_be_primary_key);"

activescaffold - filtering lists with custom methods

Posted by chetan
on Monday, October 22
These days I am using activescaffold plugin to build an admin portal for one of the RoR projects I work on. We have around 30+ tables, 30+ primary keys or unique indices and 60+ foreign keys, and most of the tables don't follow activerecord conventions of having primary key as 'id' etc thus it is moreover porting an admin portal for legacy system on RoR.

While building this portal I had to create custom methods which filter, based on indices, the data list. Now, creating custom methods is not a grind in activescaffold but filtering list is :-

Solution
  • add a custom method - suppose "filter_by_foreign_key_2"
  • copy paste the 'find_page' method from vendor/plugins/active_scaffold/lib/finder.rb to your controller - this overrides the 'find_page' method
  • in your controller create this custom method "filter_by_foreign_key_2" and call 'list' method
        def filter_by_foreign_key_2
          list
        end
        
  • add below lines to 'find_page' in your controller so that we specify which condition to use when action is "filter_by_foreign_key_2"
        case params[:action]
          when "filter_by_foreign_key_2" : condition = "foreign_key='yell'"
        end
    
  • now, find text 'finder_options' in 'find_page' method and change
    :conditions => all_conditions
    to
    :conditions => condition