Skip to content

Instantly share code, notes, and snippets.

@theotherzach
Last active May 29, 2020 17:30
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save theotherzach/5130140 to your computer and use it in GitHub Desktop.
Save theotherzach/5130140 to your computer and use it in GitHub Desktop.
Rails 4 and Postgres: Getting HStore and Array
class AddHstoreExtension < ActiveRecord::Migration
def up
execute 'CREATE EXTENSION hstore'
end
def down
execute 'DROP EXTENSION hstore'
end
end
class CreateDueDates < ActiveRecord::Migration
def change
create_table :due_dates do |t|
t.string :name
t.text :description
t.date :start
t.string :tags, array: true
t.hstore :recur
t.timestamps
end
end
end
<div class="field">
<%= f.label :tags %><br />
<%= f.collection_check_boxes :tags, %w[CAT Payroll Sales School City State Federal], :to_s, :to_s %>
</div>
<div class="field">
<%= f.label :frequency %><br />
<%= f.collection_select :frequency, %w[Daily Weekly Monthly Quarterly Annualy], :to_s, :to_s %>
</div>
class DueDate < ActiveRecord::Base
store_accessor :recur, :frequency
store_accessor :recur, :day_of_week
store_accessor :recur, :day_of_month
end
class DueDatesController < ApplicationController
before_action :set_due_date, only: [:show, :edit, :update, :destroy]
def index
@due_dates = DueDate.all
end
def show
end
def new
@due_date = DueDate.new
end
def edit
end
def create
@due_date = DueDate.new(due_date_params)
respond_to do |format|
if @due_date.save
format.html { redirect_to @due_date, notice: 'Due date was successfully created.' }
format.json { render action: 'show', status: :created, location: @due_date }
else
format.html { render action: 'new' }
format.json { render json: @due_date.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @due_date.update(due_date_params)
format.html { redirect_to @due_date, notice: 'Due date was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @due_date.errors, status: :unprocessable_entity }
end
end
end
private
def set_due_date
@due_date = DueDate.find(params[:id])
end
def due_date_params
params.require(:due_date).permit(
:name, :description, :start, { :tags => [] }, :recur,
:day_of_month, :day_of_week, :frequency
)
end
end
@erpe
Copy link

erpe commented Mar 5, 2014

you could shorten your strong params with:

params.require(:due_date).permit( :name, :description, :start, { tags: [] }, DueDate.stored_attributes[:recure] )

@mwmeyer
Copy link

mwmeyer commented Jul 31, 2014

I had to use this syntax to get the hstore to work for Rails 4.1.4:
params.require(:due_date).permit(recure: DueDate.stored_attributes[:recure] )

@alanchavezgar
Copy link

Thank you!

@QQism
Copy link

QQism commented Jun 10, 2015

@mwmeyer you saved my day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment