Rails 耙选项

rake --tasks  # lists all possible activities

Rails Rake迁移迁移创建表示例

	      class AddEntriesTable < ActiveRecord::Migration
          def self.up
            create_table :entries do |table|
              table.column :title, :string
              table.column :content, :text
              table.column  :created_at, :datetime
            end
          end

          def self.down
            drop_table :entries
          end
        end

Rails 3列表中的radiobox集合

<p>Contact:<br/>
<table class="tbl">
  <% cells = 0 %>
  <% Contact.find(:all).each do |c| %>
    <% cells += 1 %>
    <% if cells.divmod(3)[1] == 1 -%><tr><% end -%>  
    <td><input type="radio" name="task[contact_id]" value="<%= c.id -%>" 
	<% if @task.contact == c -%> checked="checked" <% end -%> />
	<%= c.name %></td>
	<% if cells.divmod(3)[1] == 0 -%></tr><% end -%>
  <% end %>
</table>
</p>

Rails 复选框,在3列表中选中关联的值

<p>Companies:<br/>
<table class="tbl">
  <% cells = 0 %>
  <% Company.find(:all).each do |c| %>
    <% cells += 1 %>
    <% if cells.divmod(3)[1] == 1 -%><tr><% end -%>  
    <td><input type="checkbox" name="technology[company_ids][]" value="<%= c.id -%>" 
    <% if @technology.companies.include?(c) -%> checked="checked" <% end -%> />
    <%= c.name %></td>
    <% if cells.divmod(3)[1] == 0 -%></tr><% end -%>
  <% end %>
</table>
</p>

Rails 生成随机域名

  def domain_name
    [
      "www",
      ("a".."z").to_a.sort_by{rand}.join.slice(0..rand(15)),
      %w{com net org}[rand(3)]
    ].join('.').downcase    
  end

Rails content_tag(已修改):第2部分(视图)

<%= content_tag 'div', :class => 'products' do
	content_tag 'ul', :class => 'list' do
		content_tag 'li', :class => 'item1'
		content_tag 'li', :class => 'item1'
	end
end
%>

Rails 通过闪光循环

<% flash.each do |key, msg| %>
  <%= content_tag :div, msg, :id => key %>
<% end %>

Rails 计数器缓存列

class AddTaskCount < ActiveRecord::Migration
  def seld.up
    add_column :projects, :tasks_count, :integer, :default => 0
    Project.reset_column_information
    Project.find(:all).each do |p|
      p.update_attribute :tasks_count, p.tasks.length
    end
  end

  def self.down
    remove_column :projects, :tasks_count
  end
end

--

class Task < ActiveRecord::Base
  belongs_to :project, :counter_cache => true
end

Rails Rails错误已本地化

<% if !@object.errors.empty? %>
  <div class="errorExplanation" id="errorExplanation">
    <ul>
      <% for e in @object.errors %>
      <li><%= e[1] %></li>
      <% end %>
    </ul>
  </div><br />
<% end %>

Rails check_name_syntax

    def check_name_syntax
      !!((first_name + last_name).strip =~ /^[a-z '.-]+$/i)
    end