Yu-Chieh’s Blog (Y.C. Chang)

Ruby on Rails / Rubygems / FullStack / Git / Mac notes.

Rails Project Rake Tips

  • Rails image disappears with error: Failed to load resource:
  • net::ERR_CONTENT_LENGTH_MISMATCH
1
$ rake tmp:clear # for recompile asset tmp

Rails Console Tips: Table Operations

In rails console, you can

list tables

1
> ActiveRecord::Base.connection.tables

list a table structure (but it is a protected method)

1
2
3
4
5
6
# this dose not work. 
> ActiveRecord::Base.connection.table_structure("projects")

# we should utilize send method to call protected method
> @c = ActiveRecord::Base.connection
> @c.send(:table_structure, "xxxs") # xxxs is your model name

show table schema

1
> ActiveRecord::Base.connection.columns :table_name

Rails Scaffold Create .erb Rather Thean .haml After Bundling Rails-haml Gem

  • After bundling ‘rails-haml’ gem, all views generated by scaffold are .haml. If we want to use default .erb views file, we need to append the folowing lines in your config/application.rb file or in config/enviroments/developement.rb.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# application.rb
...
module Events
  class Application < Rails::Application

....
# append to here
    config.generators do |g|
       g.template_engine :erb
    end
....

  end
end
...

Generate Html Table From Array or Hash

  • install gem builder
1
$ gem install builder
  • Use Builder for generate HTML table
1
2
3
4
5
6
7
8
9
10
11
# Use the XMLBuilder for this:

require 'builder'

data = [{"col1"=>"v1", "col2"=>"v2"}, {"col1"=>"v3", "col2"=>"v4"}]
xm = Builder::XmlMarkup.new(:indent => 2)
xm.table {
  xm.tr { data[0].keys.each { |key| xm.th(key)}}
  data.each { |row| xm.tr { row.values.each { |value| xm.td(value)}}}
}
puts "#{xm}"

Rails Object to Hash

1
2
3
4
5
6
7
8
9
10
$ rails c
# irb
# Model object -> hash
> @post = Post.first
> @post.attributes

# OpenStruct object -> hash
> @post = OpenStruct.new(title:"this is title", description:"Hello world!")
> @post.to_h
# equals to -> ActionController::Parameters.new(@p.to_h)

How to Use Command Line Show Git Tree

1
2
3
4
5
6
$ git log --pretty=oneline --graph --decorate --all
$ git log --oneline --graph --decorate --all
$ gitk --simplify-by-decoration --all
$ gitk --all
$ git show-branch --all
$ git log --all --graph --decorate --oneline --simplify-by-decoration

Dynamic Form Implementing Note

1
2
3
4
5
$ rails g scaffold product name price:decimal
$ rails g scaffold product_type name
$ rails g scaffold product_field name field_type required:boolean product_type:belongs_to
$ rails g migration add_type_to_product product_type:belongs_to properties:text
$ rake db:migrate
1
2
3
4
5
6
7
# config/routes.rb
...
  resources :product_types

  resources :products
  root 'products#index'
...