rails – generic error dialogs with bootbox.js

We started adding some ajax foo to one rails app I’m working on and I was looking for an simple way to add modal dialogs when an error occurred. Luckily, @makeusabrew created bootbox.js and the bootbox-rails gem.

First the standard install instructions from the gem page
Update your Gemfile

    gem 'bootbox-rails', '~>0.1.0'

Now you need to edit your app/assets/javascripts/application.js file and add the following line:

  //= require boot box

Now a generic javascript function to handle ajax errors

function error_modal_ajax(jqXHR, textStatus, errorThrown){
	
    switch(jqXHR.status) {
    case 401:
    	dialog_message = "textStatus<br />";
    	dialog_message = "Your session has timed out. Please login again.";
    	dialog_label = "Login";
	    bootbox.dialog(dialog_message, {
			"label" : dialog_label,
			"class" : "success", // or primary, or danger, or nothing at all
			"callback": function() {
				window.location = "/";
			}
		});
        break;
    default:
    	dialog_message = "textStatus<br />";
    	dialog_message += "This is embarassing, an error occured. If this happens again, please contact support for assistance.";
    	bootbox.dialog(dialog_message);
	}   
}

Now, update all your error callbacks in ajax calls

$.ajax(REST_URL, {
  type: 'GET',
  dataType: 'json',
  cache: false,
  error: function(jqXHR, textStatus, errorThrown) {
    error_modal_ajax(jqXHR, textStatus, errorThrown);
  },
  success: function(data, textStatus, jqXHR) {
   ...		          
  }

You can see when a 401(Unauthorized) code is returned, a “login” button appears and your directed to the home page which displays a login form. The next thing I want to do is add a login form in the modal dialog.

Hope this helps.

rails: Save Ransack search queries

My ransack AJAX searching doesn’t save your search parameters across transactions, a usability pain in the arse! In this post I’ll show you how to easily add this capability in a generic way.

In a previous post rails – AJAX Search, Sort, Paginate with Ransack and Kaminari I added AJAX search ability to index pages.

def index
  @search = ComponentDefinition.search(search_params)
  # make name the default sort column
  @search.sorts = 'name' if @search.sorts.empty?
  @component_definitions = @search.result().page(params[:page])
end

I added methods(search_params, clear_search_index) in the ApplicationController to add a level of abstraction from the search gem I was using. Turns out this made things super easy, especially considering I won’t have to update my code generation tools for index pages.

class ApplicationController < ActionController::Base
  def search_params
    params[:q]
  end
  def clear_search_index
    if params[:search_cancel]
      params.delete(:search_cancel)
      if(!search_params.nil?)
        search_params.each do |key, param|
          search_params[key] = nil
        end
      end
    end
  end
end

I decided to store the ransack search parameters, params[:q], in the session. To make the session parameter unique I used a key creed from the controllers name and “_search”.

class ApplicationController < ActionController::Base

  # CHECK THE SESSION FOR SEARCH PARAMETERS IS THEY AREN'T IN THE REQUEST
  def search_params
  	if params[:q] == nil
  		params[:q] = session[search_key]
  	end
  	if params[:q]
		  session[search_key] = params[:q]
		end
		params[:q]
  end
  # DELETE SEARCH PARAMETERS FROM THE SESSION
  def clear_search_index
	  if params[:search_cancel]
	  	params.delete(:search_cancel)
	  	if(!search_params.nil?)
		    search_params.each do |key, param|
		    	search_params[key] = nil
	    	end
	    end
	    # REMOVE FROM SESSION
	    session.delete(search_key)
	  end
  end

protected
  # GENERATE A GENERIC SESSION KEY BASED ON TEH CONTROLLER NAME
  def search_key
    "#{controller_name}_search".to_sym
  end
end

I broke some Scrum rules by implementing this user story that wast planned in the current Sprint. The lack of this basic feature was making my testing unbearable! Also, I time boxed it to an hour and it took about 20 minutes including google-foo’n this article .

rails: showing association details with bootstrap modal

The first releases of my app was focused on the data model. Because of that we use standard CRUD pages and added reporting functionality for more detailed inspection of data. Since the model is relational, using CRUD pages makes it difficult to enter data at multiple levels of the relationships. We ended up with a simple UI where you need intimate knowledge of the data model, not good. Well we knew this was going to happen so these next releases will have some usability focus.

The first usability improvement we’re making is showing associated data in a modal dialog instead of clicking through to the show page of the associated model.

This example will demonstrate displaying details of a source from a cost’s show page. A cost belongs_to a source, source has_one cost. This means we will navigate to a Cost’s show page and click something to show the details of the cost.

Gemfile
We are using Rails 4 and Bootstrap 2.3.

gem 'rails', '~> 4.0.1'
gem 'bootstrap-sass', '2.3.1.0'
gem 'sass-rails', '4.0.2'

Sources Controller
Below, is a snippet from the app/controllers/sources_controller.rb, this is the controller that will handle the ajax request for the details of a given source.
When a request comes in ending in “.js” (/sources/1.js) the _detail partial will be returned.

The app/view/sources/_detail.html.erb partial displays the details of the source. I also changed app/view/sources/show.html.erb to render the _details partial for code reuse.

def show
  respond_to do |format|
    format.html
    format.json
    format.js {
      render '_detail', :locals => {:source => @source}
    }
  end
end

Cost Detail Partial

Pretty simple, put your view code here. Again, you might want your show page to render this partial.

Generic Detail Modal
This works by inserting html returned from the AJAX call in detail-modal-body div.

<div id="detail-modal" class="modal fade hide" tabindex="-1" role="dialog" aria-labelledby="detail-modal-label" aria-hidden="true">
	<div class="modal-dialog">
	  <div class="modal-content">
	    <div class="modal-header">
	    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	      <h4 class="modal-title" id="detail-modal-label">Detail</h4>
	    </div>
	    <div class="modal-body">
	    	<div id="detail-modal-body"></div>
		</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Historical Cost Show
In app/historical_costs/show.html.erb I replaced the link to the source show page with a button to a modal dialog. You’ll also need to render the generic detail_modal.html


<%= @historical_cost.try(:source).try(:name) %>
  <% if @historical_cost.try(:source) %>
    <% source = @historical_cost.source %>
    <button class="btn btn-link" data-toggle="modal" data-target="#detail-modal" 
      onclick="showDetailDialog('<%=Source.name.pluralize.underscore %>', '<%= source.id %>')">
      <%= source.try(:name)%>
    </button>
<% end %>

<%= render 'shared/detail_modal.html'%>

Notice the ‘on click’ event is calling a javascript method, showDetailDialog. Yeh, I would have rather done it with 100% unobtrusive javascript but it’s my understanding that bootstrap 2.x events model can’t pass data-* attributes. If I’m wrong please let me know.

AJAX Request & Callbacks
100% unobtrusive javascript aside, The method below can be used for any model as long as you have implemented the controller and a detail partial for your model.

     function showDetailDialog(model, id) {
	var request = $.ajax({
		url: '/'+model+'/' + id + '.js',
		cache: 'false',
		dataType: 'html',
		type: 'GET'
	});
	request.done(function( msg ) {
		$( "#detail-modal-body" ).html( msg );
	});
	request.fail(function( xhr, textStatus ) {
		var msg = "<h3>Request failed: " + textStatus +"</h3>";
		msg +="<h3>Ready State: "+xhr.readyState+"</h3>";
		msg+= "<h3>Status: "+xhr.status+"</h3>";
		// msg += "<h3>Response Text:</h3>"+xhr.responseText;
		$( "#detail-modal-body" ).html( msg );
	});
   }

Notice the model passed in is used to build the web service endpoint URI and I set cache to false since the dataType is html.
Future Enhancements

  • detail partial: I want to make this generic so generators create it when you generate scaffolding.
  • Currently the modal title is static, I would like to dynamically display the model’s name in the modal title instead.

Next thing I need to figure out is posting forms in a modal using AJAX.

Resources

rails: switching between connections

In the app I’m working on we are allowing certain roles the ability to create reports. Keeping things simple, the user basically enters some sql which, in-turn, populates worksheets in and Excel file. Of course this sounds dangerous since a user could update or even delete data.

To mitigate this risk we created a separate postgres user, report, which is used to execute the sql statements and only has grants for select. We updated our chef scripts to create this user with proper grants, we won’t show that here.

This is how the rails code was changed:

Update database.yml

I added an entry for each environment which used the read-only database user.

development_report:
adapter: postgis
encoding: unicode
database: bike
pool: 5
username: report
password: 12345678
timeout: 5000
host: localhost
schema_search_path: "public,postgis"
#just for test and dev
script_dir: /opt/local/share/contrib/postgis-1.5

Update code executing sql report

Notice, I wrapped the code executing the queries in a begin/ensure block because I wanted to make sure the connection was always switched back. Also, I’m not catching the exception because the caller is handling it.

def generate_report(report, filters)
  begin
    report_con_pool = ActiveRecord::Base.establish_connection("#{Rails.env}_report")
    report_con = report_con_pool.connection</code>

    result = report_con.execute(sqlTemplate)
    # ITERATE THROUGH RESULTS

  ensure
    # SWITCH BACK TO DEFAULT CONNECTION
    ActiveRecord::Base.establish_connection("#{Rails.env}")
  end # BEGIN
end

postgres: drop users with default privileges

For my rails app I need a couple users one is used when running and creating reports using sql. To avoid someone deleting data I wanted to give the ‘report’ user readonly capabilities. During testing of creating this user I made some mistakes and needed to drop the user.


postgres=# drop user report;
ERROR:  role "report" cannot be dropped because some objects depend on it
DETAIL:  privileges for default privileges on new relations belonging to role postgres in schema public
6 objects in database xyz_dev

Looks like I would first need to remove the default privileges I had bestowed on that user. One thing to note is you need to run this command for each database with default privileges. One of the mistakes I made was giving default privileges to the postgres database and the xyz_dev database.


# drop default privileges in postgres

postgres=# drop owned by report;

# drop default privileges in xyz_dev

postgres=# \c xyz_dev

# drop default privileges in xyz_dev

xyz_dev=# drop owned by report;

# drop the user

xyz_dev=# drop user report;

Rails – action mailer, devise per environment

Recently, I was configuring ActionMailer with devise and was surprised about the config.action_mailer.default_url_options configuration setting and wanted to document it.

default_url_options
This configuration parameter is found in each environmental configuration file located in ./config/environments.

I initially thought this told ActionMailer what to use for sending mail. I was wrong, this parameter is used to resolve named routes, such as devise’s edit_password_url.

smtp_settings & sendmail_settings
If you need to configure where to send the mail look into these configuration parameters.

Who is sending your emails?

If your like me, you probably want your app to send emails from different email addresses for each environment. Since this is a devise specific setting you’ll need to update config.mailer_sender in config/initializers/devise.rb

  config.mailer_sender = 'dev@example.com'
  if Rails.env.test?
    config.mailer_sender = 'test@example.com'
  elsif Rails.env.production?
    config.mailer_sender = 'prod@example.com'
  end

REFERENCES

rails – validation of cocoon nested forms

We are using cocoon for nested forms and client_side_validations for validation. We have a model, Material, which belongs to two other models, Component & Material Type.

Standard rails validations worked well in the Material form:

  belongs_to :component
  belongs_to :material_type, :class_name=>"GenericTypeItem"
	
  validates :material_type_id, presence: true, :uniqueness => {:scope => :component}
  validates :percentage, numericality: true, allow_nil: true

You can see from the above validations, :uniqueness => {:scope => :component}, MaterialType and Component need to be set and they need to be unique, pretty sweet.

This works great for the Material form but in the Component create there’s a problem. The problem is when validation occurs the Materials and Component are not in the database yet so the uniqueness validation fails to work.

To fix this we wrote a custom validator that will check for the existence of duplicate MaterialTypes for the Component. Since we have this pattern elsewhere in the app we made it generic.

In the Component model we added the following :

validates_uniqueness :materials, { :attribute_name => 'material_type_id'}

This uniqueness validation makes sure each Material in the materials attribute has unique material_type_id. The validator looks like this:

def self.validates_uniqueness(*attr_names)
  # Set the default configuration
  configuration = { :attribute_name => "name", :message => I18n.t("validation.duplicate") }
	    
  # Update defaults with any supplied configuration values
  configuration.update(attr_names.extract_options!)
	    
  validates_each(attr_names) do |record, record_attr_name, value|
    duplicates = Set.new
    attr_name = configuration[:attribute_name]
    value.map do |obj|
      cur_attr_value = obj.try(attr_name)
      if(duplicates.member?(cur_attr_value))
        # mark the record as in error so validation will detect a failure
        record.errors.add(record_attr_name, "")
        obj.errors.add(attr_name, :message)
      else
        duplicates.add(cur_attr_value)
      end
    end
  end      

Take a close look at the code which marks the invalid Materials :

record.errors.add(record_attr_name, "")
obj.errors.add(attr_name, :message)

One gotcha that we discovered was it is not sufficient to mark the nested model, Material, as invalid alone. You also need to mark the Component’s attribute, in this case materials, as invalid.

rails – AJAX Search, Sort, Paginate with Ransack and Kaminari

We wanted to add searching and sorting to our paginated tables and came across lots of railscasts on how to do it:

This post will cover getting ransack (search & sorting) and kaminari(pagination) working in my rails 4 app. I also added a “clear search” feature.

Before we go any further I’ll show you what the table will look like at the end

ransack_kaminari_bootstrap_table

Technology Stack

ruby '2.0.0'
gem 'rails', '4.0.1'
# css
gem 'bootstrap-sass', '2.3.1.0'
gem 'bootswatch-rails', '0.5.0'
gem 'kaminari-bootstrap', '~> 0.1.3'
# table search and sort
gem "ransack", github: "activerecord-hackery/ransack", branch: "rails-4"
# table pagination
gem 'kaminari'

Ransack

As stated earlier Ransack is sick (ie a slick timesaver, not cough cough sick)! it allows you to easily add searching and sorting. Other gems/frameworks allow you to do this but ransack sets itself apart by seamlessly handling associations.

Controller

before_action :clear_search_index, :only => [:index]

def index
  @search = Component.search(search_params)
  # make name the default sort column
  @search.sorts = 'name' if @search.sorts.empty?
  @component = @search.result().page(params[:page])
end

Application Controller

For usability, I added a clear search button next to the search button. To clear the search we’re setting the values of the hash in params[:q] to nil & deleting the :search_cancel parameter I added, pretty simple.

def search_params
  params[:q]
end

def clear_search_index
  if params[:search_cancel]
    params.delete(:search_cancel)
    if(!search_params.nil?)
      search_params.each do |key, param|
        search_params[key] = nil
      end
    end
  end
end

index.html.erb

<% provide(:title, Component.model_name.human.pluralize) %>
<h1><%= Component.model_name.human.pluralize %></h1>
<div class="row">
  <%= link_to t("basic.create.type", type: Component.model_name.human ), new_component_path, class: "btn btn-success pull-right" %>
</div>

<div id="components"><%= render 'components' %></div>

index.js.erb

$('#components').html('<%= escape_javascript(render("components")) %>');

_components.html.erb

<%= search_form_for @search, :remote=>"true", url: components_path, :method => :get do |f| %>
  <table class="table table-striped table-bordered table-condensed table-hover">
    <thead>
    <tr>
      <th class="component_name_header_col">
        <%= sort_link @search, :name, get_label("component", "name"), {}, { :remote => true, :method => :get } %>
      </th>
      <th class="component_component_definition_name_header_col">
        <%= sort_link @search, :component_definition_name, get_label("component", "component_definition"), {}, { :remote => true, :method => :get } %>
      </th>
      <th class="component_manufacturer_name_header_col">
        <%= sort_link @search, :manufacturer_name, get_label("component", "manufacturer"), {}, { :remote => true, :method => :get } %>
      </th>
      <th class="component_source_name_header_col">
        <%= sort_link @search, :source_name, get_label("component", "source"), {}, { :remote => true, :method => :get } %>
      </th>
      <th class="component_level_type_name_header_col">
        <%= sort_link @search, :level_type_name, get_label("component", "level_type"), {}, { :remote => true, :method => :get } %>
      </th>
      <th class="action_col"><%= t("basic.action") %></th>
    </tr>
    <tr>
      <th><%= f.text_field :name_cont %></th>
      <th><%= f.text_field :component_definition_name_cont %></th>
      <th><%= f.text_field :manufacturer_name_cont %></th>
      <th><%= f.text_field :source_name_cont %></th>
      <th><%= f.text_field :level_type_name_cont %></th>
      <th><%= render  partial: 'shared/search_button_group'%></th>
    </tr>
    </thead>
    <tbody>
<% @component.each do |component| %> <% end %>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th class="component_name_header_col"><%= sort_link @search, :name, get_label("component", "name"), {}, { :remote => true, :method => :get } %></th>
<th class="component_component_definition_name_header_col"><%= sort_link @search, :component_definition_name, get_label("component", "component_definition"), {}, { :remote => true, :method => :get } %></th>
<th class="component_manufacturer_name_header_col"><%= sort_link @search, :manufacturer_name, get_label("component", "manufacturer"), {}, { :remote => true, :method => :get } %></th>
<th class="component_source_name_header_col"><%= sort_link @search, :source_name, get_label("component", "source"), {}, { :remote => true, :method => :get } %></th>
<th class="component_level_type_name_header_col"><%= sort_link @search, :level_type_name, get_label("component", "level_type"), {}, { :remote => true, :method => :get } %></th>
<th class="action_col"><%= t("basic.action") %></th>
</tr>
<tr>
<th><%= f.text_field :name_cont %></th>
<th><%= f.text_field :component_definition_name_cont %></th>
<th><%= f.text_field :manufacturer_name_cont %></th>
<th><%= f.text_field :source_name_cont %></th>
<th><%= f.text_field :level_type_name_cont %></th>
<th><%= render partial: 'shared/search_button_group'%></th>
</tr>
</thead>
<tbody>
<tr>
<td class="component_name_body_col"><%= component.try(:name) %></td>
<td class="component_component_definition_body_col"><%= component.component_definition.try(:name) %></td>
<td class="component_manufacturer_body_col"><%= component.manufacturer.try(:name) %></td>
<td class="component_source_body_col"><%= component.source.try(:name) %></td>
<td class="component_level_type_body_col"><%= component.level_type.try(:name) %></td>
<td>
<div class="btn-group"><a class="btn dropdown-toggle btn-primary action-btn" href="#" data-toggle="dropdown">
 <%= t('basic.action') %>

 </a>
<ul class="dropdown-menu">
	<li><%= link_to t('basic.show.simple'), component %></li>
	<li><%= link_to t('basic.edit.simple'), edit_component_path(component) %></li>
	<li><%= link_to t('basic.destroy.simple'), component, method: :delete, data: { confirm: 'Are you sure?' } %></li>
</ul>
</div>
<!-- button group --></td>
</tr>
</tbody>
</table>
<%= paginate @component %>
<% end %>

Kaminari

A note on using kaminari and will_paginate. I’m not sure this is possible. I was originally using will_paginate but it does not work with ransack, w/o writing java-ick(my alias for javascript). I had removed will_paginate from the Gemfile but had forgotten to run bundle install.

The side affect was the values in config/initializers/kaminari_config.rb were not being used but WillPaginate.per_page was being used by kaminari, pretty weird.

Anyways here’s what the kaminari config file looks like.

Kaminari.configure do |config|
  config.default_per_page = 5
  # config.max_per_page = nil
  # config.window = 4
  # config.outer_window = 0
  # config.left = 0
  # config.right = 0
  # config.page_method_name = :page
  # config.param_name = :page
end

The query

When we first started looking into this we examined using a combination of join and merges to create one query. It was a great exercise in extending our understanding but it looks like ransack is doing this for us.

The first query is searching on name and level type with default sorting on name. Limit is 5 due to kaminari configuration. We are using postgres so ilike is being used for a case insensitive search.

SELECT "component".* FROM "component" 
LEFT OUTER JOIN "generic_type_item" 
  ON "generic_type_item"."id" = "component"."level_type_id" 
WHERE (("component"."name" ILIKE '%e%' AND "generic_type_item"."name" ILIKE '%a%')) 
ORDER BY "component"."name" ASC LIMIT 5 OFFSET 0

The next query was generated after clicking the sort icon, notice the only change is the ORDER BY, from ASC to DESC.

SELECT "component".* FROM "component" 
LEFT OUTER JOIN "generic_type_item" 
  ON "generic_type_item"."id" = "component"."level_type_id" 
WHERE 
   (("generic_type_item"."name" ILIKE '%a%' 
    AND "component"."name" ILIKE '%e%')) 
ORDER BY "component"."name" DESC LIMIT 5 OFFSET 0

Routes

If your concerned the request length will be too long with all the search filtering you can use a POST instead of a GET, I didn’t. If you use POST rather than GET you’ll have to update your routes.

rails – postgis and your models

We’re going to look at how to store a PostGIS, install PostgreSQL and PostGIS,  point using ActiveRecord and activerecord-postgis-adapter gem.

I followed the Geo-Rails Part 2 by @danielazuma post to create a model with a point attribute.  The tutorial then shows how easy it is to perform GIS queries but doesn’t get into the details of CRUD functionality through the web-site, this is where I’ll pick-up.

I’ll cover some of the tutorial here to get you started. if you want to see the GIS queries checkout Geo-Rails Part 2 by @danielazuma, his other post are great also, thanks Daniel!

Before we get started one thing I found confusing in Daniel’s tutorial is he calls the point attribute lat_long when in fact to insert data into the column the format is “POINT( LONGITUDE, LATITUDE). For my tutorial I’m calling the attribute location and the user will enter long, lat to make it consistent.

Create a migration specifying a location attribute as type point…

rails g migration port name:string location:point

Change the migration to make the location column geographic

class CreatePorts < ActiveRecord::Migration   def change    create_table :port do |t|      t.string :name      t.point :location, :geographic => true
     t.timestamps
   end
  end
end

Update the Model…

Let’s look at the Port model, there are several things we changed/updated.

class Port < ActiveRecord::Base   include PointsHelper   set_rgeo_factory_for_column(:location, RGeo::Geographic.spherical_factory(:srid => 4326))

  validates :location, format: { with: VALID_LONG_LAT_DIRECTION, message: I18n.t("validation.point") }
  def location
    point_to_s(self[:location])
  end
  def location=(s)
    # Parse "s" or do whatever you need to with it
    # then set your real attribute.
    self[:location] = create_point(s)
  end

Validation needs to be added for the specific format(s) my customer wanted, i.e. 104.9847° W, 29.7392° N. The Port.location attribute ends up being a RGeo::Geographic::SphericalPointImpl object.  I stored the validation format regex in ./config/initializers/constants.rb as a constant VALID_LONG_LAT_DIRECTION.

VALID_LONG_LAT_DIRECTION = /\A(\d*.\d*)(\xC2\xB0)(\s*)(\w),(\s*)(\d*.\d*)(\xC2\xB0)(\s*)(\w)\z/

Also notice I’m internationalizing the message using I18n.t(“validation.point”), the message is located in ./config/locales/en.yml. I’m keeping all my validation messages under validation:

validation:
  point: "should be longitude, latitude with direction, i.e. 39.7392° N, 104.9847° W"

Location Getter & Setter

The location attribure is actually a RGeo::Geographic::SphericalPointImpl object, because of this we need to perform translations to and from an rgeo point implementation and the formatted string.

To translate between a point object and string I overrode location getter and setter. So I can use these translation methods in other models I created a PointsHelper, it’s included in first line of the model.  The PointsHelper methods are s_to_point and point_to_s. Implementation of these methods is left as an exercise for the reader (I know I hate when people do that, just spoon feed me dammit!…)

Views
Since we overrode the location getter and setter only the form partial, _form, needs to be updated.

The form partial for location looks like this…

<div class="field">
  <%= f.label "location" %>
  <%= f.text_field :location, :value => @port.location %>
</div>

The change here is  :value => @port.location. If we don’t add :value the  getter is not called and the web page displays the value as seen  in the database, 0101000020E6100000C2172653053F5A40053411363CBD3D40.

So now we have a way to enter and view GIS points with in the rails framework. In the near future I’m sure I’ll need to plot these points on a map.

postgres – install with brew

  • download brew, http://brew.sh/
  • uninstall previous versions of postgres
    • this can be a pain depending how you installed it
  • brew install postgres
  • copy the output for documentation, you can also run brew info postgres
  • modify your path(~/.profile)
    • export POSTGRES=/usr/local/Cellar/postgresql/9.3.1
    • export PATH=…$POSTGRES/bin:$PATH (/usr/bin is AFTER POSTRGRES path)
  • initdb /usr/local/var/postgres -E utf8
  • create aliases cause my mind don’t work so well
    • alias postgres.start=’pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start’
    • alias postgres.stop=’pg_ctl -D /usr/local/var/postgres -m fast stop’
  • create postgres id ( brew creates a postgres user with the user/pwd you installed postgres with, $ORIGINAL_USER)
    • TO CONNECT USE : psql -U mbahl -W postgres
    • CREATE ROLE postgres SUPERUSER LOGIN PASSWORD ‘WHAT-EVER’
  • Modify /usr/local/var/postgres/pg_hba.conf to set METHOD from trust to md5
  • Restart postgres
    • postgres.stop (see above)
    • postgres.start (see above)
  • drop role $ORIGINAL_USER
  • brew install postgis