Rails 选中关联值的复选框

<% Company.find(:all).each do |c| %>
<input type="checkbox" name="technology[company_ids][]" value="<%= c.id %>" 
<% if @technology.companies.include?(c) -%> checked="checked" <% end -%> />
<%= c.name %></td>
<% end %>

Rails radiobox集合

<% Company.find(:all).each do |c| %>
  <input type="radio" name="technology[company_id]" value="<%= c.id -%>" 
  <% if @technology.company == c -%> checked="checked" <% end -%> />
  <%= c.name %></td>
<% end %>

Rails 使用RMagick上传并调整大小

require 'RMagick'
class Profile < ActiveRecord::Base
  belongs_to :user
  
  #image = the image passed from params[:image]
  #file_type = the confirmed filetype from the controller
  #current_user = various information about the current user
  def self.upload(image, file_type, current_user)
    #set default cols and rows for our two images that will be created from the uploaded user image
    img_size = {:main =>{:cols => 250,:rows => 375},
          :thumb =>{:cols =>80, :rows =>120}
         }
    #set base directory for the users image
    imgDir = "#{RAILS_ROOT}/public/images/user_images"
    #set the base name for our userimage
    userImg = " #{current_user.login}-#{current_user.id}"
    #loop through the image dir and delete any old user images
    Dir.foreach(imgDir){|file|
    if file.to_s.include?(userImg)
      File.unlink("#{imgDir}/#{file}")
    end
    }
    #read the image from the string
    imgs = Magick::Image.from_blob(image.read)
    #change the geometry of the image to suit our predefined size
    main_image = imgs.first.change_geometry!("#{img_size[:main][:cols]}x#{img_size[:main][:rows]}") { |cols, rows, img|
       #if the cols or rows are smaller then our predefined sizes we build a white background and center the image in it
     if cols < img_size[:main][:cols] || rows < img_size[:main][:rows]
      #resize our image 
      img.resize!(cols, rows)
      #build the white background
      bg = Magick::Image.new(img_size[:main][:cols],img_size[:main][:rows]){self.background_color = "white"}
      #center the image on our new white background
      bg.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)

     else
      #in the unlikely event that the new geometry cols and rows match our predefined size we will not set a white bg
        img.resize!(cols, rows)
     end
      }
    main_image.write "#{imgDir}/#{userImg}.#{file_type}"

    thumb = imgs.first.change_geometry!("#{img_size[:thumb][:cols]}x#{img_size[:thumb][:rows]}") { |cols, rows, img|
       if cols < img_size[:thumb][:cols] || rows < img_size[:thumb][:rows]
      img.resize!(cols, rows)
      bg = Magick::Image.new(img_size[:thumb][:cols],img_size[:thumb][:rows]){self.background_color = "white"}
      bg.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)

     else
        img.resize!(cols, rows)
     end
      }
    thumb.write "#{imgDir}/#{userImg}-thumb.#{file_type}"
    if FileTest.exist?("#{imgDir}/#{userImg}.#{file_type}")
    return "The file was written and its name is #{userImg}.#{file_type}"
    else
    return false
    end
  end
end

Rails 无法弄清楚为什么Rails不会在服务器上启动

rake db:migrate RAILS_ENV=production --trace

Rails 更简单的标签

class TabHelper
  attr_reader :html, :tabs

  def initialize(template, states)
    @template = template
    @states = states
    @html = []
    @tabs = {}
  end

  def add(action, text)
    url = { :action => action }
    html = 
      if @template.request.path.sub(/\?.*/, '') == @template.url_for(url)
        @states[:active].call(text, url)
      else
        @states[:inactive].call(text, url)
      end
    @tabs[action] = html
    @html << html
  end
  alias_method :[]=, :add
  
  def [](*args)
    @tabs.values_at(*args)
  end
end

#== Example ==

module ProductsHelper
  def subnav_links
    t = TabHelper.new(self,
      :active   => Proc.new {|text, url| %|<div class="current tab">#{text}</div>| },
      :inactive => Proc.new {|text, url| %|<div class="tab">#{link_to text, url}</div>| }
    )
    t[:index] = 'Manage Products'
    t[:front_page] = 'Manage Front Page'
    
    '<div id="tabs">' +
      '<div style="float: left">' +
        t[:index, :front_page].join +
      '</div>' +
      '<div class="clear"></div>' +
    '</div>'
  end
end

Rails auto_complete

##controller

#en algunos casos requiere un skip_before_filter para corregir un error de verify_authenticity
skip_before_filter :verify_authenticity_token, :only => :auto_complete_for_user_apellido


#auto_complete_for :modelo, :campo

auto_complete_for :user, :apellido

## config/routes.rb
map.resources :admin, :collection => {:auto_complete_for_user_apellido => :get} 

##view
<%= text_field_with_auto_complete :paciente, :nombre, {}, {:method => :get, :skip_style => true}%>

#tambien se puede pasar un javascript
<%= text_field_with_auto_complete :user, :apellido, {},:after_update_element => 'function(text, li){ alert(mensaje);}'%>

Rails Paginate与排序

  def list
    @page_title ='List books'
    # Good job!
    sort_by = params[:sort_by]
    @book_pages, @books = paginate :books, :order => sort_by, :per_page => 10
  end

Rails Rails表单

<% form_for :widget, :url=>widgets_path(@widget), :html=>{} do |f| %>

<% fields_for :person do |p| %>
	<% 5.times do |i| %>
	<%= p.select(:state, State.find(:all).collect {|s| [ s.title, s.id ], {}, {:index=>i, :style=>''}) %>
	<%= p.text_field :zip, :size=>20, :index=>i %>
	<%= 
	calendar_field "person_#{i}", 'born_string',
	{ :class => 'date', :name => "person[#{i}][born_string]", :value=>Date.today)strftime("%m/%d/%Y"), :id=>"person_#{i}_born_string" },
	{ :firstDay => 1, :range => [1900, 2008], :step => 1, :showOthers => true, :cache => true, :ifFormat => '%m/%d/%Y' }
	%>
	<%= p.country_select(:country, ['United States'], {}, :index=>i, :style=>'')%>
	<%= p.text_area :some_text_area, :cols=>45, :rows=>5, :index=>i %>								
	<% end %>
<% end %>

<%=	
calendar_field 'widget', 'created', 
{ :class=>'date', :style=>'', :name=>'widget[created]', :value=>Date.today.strftime("%m/%d/%Y") },
{ :firstDay=>1, :range=>[1900, 2008], :step=>1, :showOthers=>true, :cache=>true, :ifFormat=>'%m/%d/%Y' } 
%>

<%= f.radio_button("Active", true, :onclick=>"") %>Yes
<%= f.radio_button("In-active", false, :onclick=>"") %>No

<select name="custom_question_filter[<%=unique_per_custom_question_filter%>][dropdown_selections][]" size="<%=num_or_max(question.options.size)%>" multiple="multiple" style="border:2px solid #ccc;width:180px;">
				<%= options_for_select(question.options, custom_question_filter.dropdown_selections) %>
			</select>

<% end %>

Rails Ruby on Rails 301重定向

def old_action
headers["Status"] = "301 Moved Permanently"
redirect_to "http://www.domain.com/"
end

Rails Rails:基础知识

####################################
#Models
####################################

#Create a Model
$ ruby script/generate model ClassName attribute_name:attribute_type attribute_name:attribute_type

####################################
#Controllers
####################################

#Create a Controller
$ ruby script/generate controller ClassName action1 action2

#Remove a Controller
$ ruby script/destroy controller ClassName action1 action2

####################################
#Server
####################################

#Start an application
$ script/server

####################################
#Migrations
####################################
#Migrate does these 3 things
#1. Checks the database for the unique number of the migration is most recent
#2. It steps through the migrations that have not yet been applied, one at a time.
#3. The Self.up method is executed for each migration
$ rake db:migrate

#Rollback a Migration
$ rake db:migrate VERSION=n

#Retrieving Records by ID, not recommended but at times helpful
ModelName = (Most likely TableName)
IRB>> ModelName.find(#id)
IRB>> ModelName.find(:all)

#Retrive the Last Record
IRB>> ModelName.find(:all).last (Resource Intensive)
IRB>> ModelName.find(:first, :order => 'id DESC') (Resource Efficient)