Skip to content

Instantly share code, notes, and snippets.

View cwy007's full-sized avatar
🤔
practicing rails & vue & react & react native

willian.chan cwy007

🤔
practicing rails & vue & react & react native
View GitHub Profile

controller

if params[:status].present?
  @user_balance_logs = @user_balance_logs.where(status: params[:status])
end

view

div class="form-group col-sm-4">

Update years later: instead of a Rake task, for PostgreSQL I just use

rake db:drop db:create

and then

cat somefile.sql | psql name_of_database

Dumping is

CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well

Your add_foreign_key calls would look like:

add_foreign_key "projects", "companies", on_delete: :cascade
add_foreign_key "tasks", "projects", on_delete: :cascade
add_foreign_key "task_times", "tasks", on_delete: :cascade
Operator: @>
Description: contains
Example: ARRAY[1,4,3] @> ARRAY[3,1]
Result: t (AKA true)
Membership.where('roles @> array[?]', %w[as_champion whatever])
Membership.where('roles @> array[:roles]', :roles => some_ruby_array_of_strings)
@cwy007
cwy007 / # rails enum used as class method.md
Last active September 2, 2018 14:30
Conversation.archived # => Relation for all archived Conversations

Active Record enums

Declare an enum attribute where the values map to integers in the database, but can be queried by name.

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end
 
conversation.archived!
conversation.active? # =&gt; false

Rails

In the last blogpost about hstore we showed how to enable particular extension. This time is different (maybe easier), because array is Postgres’ data type, not an extension so there’s no need to enable that, because it’s accessible out of the box!

Migration

In two previous articles (mentioned in the introduction of this article) we created Book model and appropriate SQL schema. Let’s stick to that and extend it a little bit:

def event(description)
  puts "ALERT: #{description}" if yield
end

# 将当前文件夹加入到加载路径中
$: << File.expand_path(File.dirname(__FILE__))

# 1. load 后面的参数不是绝对路径时,load 方法会从 `$:` 中查找文件名为 `event.rb` 的文件
load 'events.rb'

类似问题

Failure/Error: it { should have_many(:users) }
ActiveRecord::StatementInvalid:
PGError: ERROR:  relation "users" does not exist

   LINE 4:              WHERE a.attrelid = '"users"'::regclass
                                           ^
   :             SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
 FROM pg_attribute a LEFT JOIN pg_attrdef d