首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > Ruby Rails >

ror学习总结6

2012-12-21 
ror学习小结61 每个controler都会在app\views下有一个相应的目录2 视图中输出debug信息 %DEBUG params %

ror学习小结6
1 每个controler都会在app\views下有一个相应的目录

2 视图中输出debug信息
<%=DEBUG params %>

  <%=debug response%>

3 页面上输出
     <%=session[:user_name]%>.....
4 XML模版
   xml = Builder::XmlMarkup.new(:indent=>2, :margin=>4)
xml.instruct!ml, :version=>"1.0", :encoding=>"utf-8"
xml.books do
  xml.book(:id=>'1') do
    xml.name('xxxx')
    xml.author('dsdsd')
    xml.price ('68')
  end
  xml.book(:id=>'2') do
    xml.name('ddddd')
    xml.author('dsd')
    xml.price ('98')
  end
end
  控制器中可以直接对响应设置
    format.xml即可

5 image_path("logo.png"); 获得图片路径

6 加载javacript库
   javascript_include_tag "prototype"
==<script type="......">
   获得某个javascript路径
      <%=javascript_path "xxx.js"%>
7 加入css
     <%=stylesheet_link_tag "xxxx.css"/>

8 定义数字格式输出
   有一系列number_with_xxxx的方法,例子
      <% @books.each do |book| %>
  <tr style='background:<%= cycle("#ECECEC","#FFFFFF")  %>'>
    <td><%=number_to_currency( book.id, :unit => "NO.", :format => "%u %

n",:precision => 0) %></td>
    <td><%= book.name %></td>
    <td><%= number_to_currency(book.price, :unit => "¥", :separator => ".",

:delimiter => ",") %></td>
    <td><%= number_to_currency(book.count, :unit => "个", :format => "%n %u")

%></td>
    <td><%= link_to '查看', book %></td>
  </tr>
  <% end %>


9 生成超连接,及表单助手类
  link_to link_to_if,link_to_unlses,form_tag等。。。。。

10 form_for
    比如控制器中
     def add
      @employee=Employee.new
     end
    表单中:
       <% form_for(@employee) do |f| %>
         ........
     这样表单提交后,直接
      def create
    @employee = Employee.new(params[:employee])

    respond_to do |format|
      if @employee.save
. ...................

11 日期和时间
    下拉日期选择框
      (选择日期)select_date方法:<%= select_date() %><br/>
(选择日期和时间)select_datetime方法:<%= select_datetime() %><br/>
(选择年)select_year方法:<%= select_year(Time.now,:field_name => 'birth') %

><br/>
(选择月)select_month方法:<%= select_month (Date.today) %><br/>
(选择日)select_day方法:<%= select_day(12) %><br/>
(选择时间)select_time方法:<%= select_time() %><br/>
(选择时)select_hour方法:<%= select_hour(5) %><br/>
(选择分)select_minute方法:<%= select_minute(15) %><br/>
(选择秒)select_second方法:<%= select_second(Time.now) %><br/>

12 自定义模版helper类
    可以在app/helpers下创建一个包含helper类的books_helper.rb文件,封装输出的方


  module BooksHelper

  def index_helper books
    html=''
   ......
end
  然后在HTML页中调用:
    <%=raw index_helper @books %>

13 cookie
    cookie[:myname]="xxxx"
   读取myname=cookid[:myname]
  删除cookies.delete :myname
cookies[:cart]={:value=>cart,:expires=>Time.now+3600}

14 flash[:notice]="xxxxx"
  跨页面传值
   <%=notice%>

15 rails异步提交表单
    <a href="ajax/new" data-remote="true" id="new">xxxx</xxx>
    将异步提交到new这个controller去处理
form_tag标记
   <% form_tag("ajax/res",:remote=>true,:id=>"f1") do%>
........
   例子:一个页面中有登陆的表单,登陆后,AJAX提交,页面其他部分不变

   def login
    username=request["user"]["name"]
    password=request["user"]["password"]

    @username = username
    @rule = "VIP用户"

    respond_to do |format|
      format.html { render :layout => false }
      format.xml  { renderml => @ajaxes }
    end
  end
  登陆后的视图:
  <br>
<div>您好<span><%= @username %></span>!</div>
<div>您的角色是<span><%= @rule %></span></div>
    登陆的表单
        <div id="login">
    <% form_tag("/ajaxes/login", :remote => true, :id => "lf") do %>
    <div>用户名:<%= text_field("user", "name", :class=>"input")  %></div>
    <div>密 码:<%= password_field("user", "password", :class=>"input")  %

></div>
    <div><button type="submit">登录</button></div>
    <% end %>
  </div>

   请求的JS
   $(function($) {
    $('#lf').bind(
        'ajax:success',
        function(data, status, xhr) {
            $("#login").html(status);
        }).bind(
        'ajax:error',
        function(xhr, status, error) {
            alert(error);
        });
});

16  文件上传
   def upload
      image=params[:img]
      content_size=image.size
      file_data=image.read
      filetype=image.content_type
      @filename=image.original_filename
      fileext=File.basename(@filename).split(".")[1]
      @time=Time.now.to_s
      timeext=File.basename(@time).split("+")[0]
      newfilename=timeext+"."+fileext
      File.open("#{Rails.root}/public/"+ newfilename,"wb"){
        |f| f.write(file_data)
      }
      flash[:notice]="文件:"+ newfilename+"上传成功。"+
          "上传时间是:"+(Time.now).to_s+
          "上传的地址是:"+ "#{Rails.root}/public/"
      render :action=>"uploadImg"
    end
   上传表单的设计
       <% form_tag "/carts/upload",:multipart => true do %>
  <%= file_field_tag(:img,:size=>"40") %>
      <%= submit_tag("上传文件") %>
  <% end %>

17 下载文件

   send_file方式:
        <%= link_to "下载文件" ,:action=> "downFile",:filename=>"#

{cart.img}.jpg" %>
    downFile控制器内容:
      def downFile
    send_file "#{Rails.root}/public/images/"+params[:filename] unless params

[:filename].blank?
  end

    send_data方式:
       def downSendData
    io=File.open("#{Rails.root}/public/images/"+params[:filename])
    io.binmode
    send_data(io.read,
   :filename=> params[:filename],
   :type=>"image.jpg",
   :disposition=>"attachment"
   )
    io.close
  end

18 使用CKEDITOR
  见 http://www.162cm.com/archives/1156.html的配置
19 使用actionmailer
   1)config下的enviroment中添加代码
    ActionMailer::Base.delivery_method=:smtp
ActionMailer::Base.default_charset="UTF-8"
ActionMailer::Base.smtp_settings={
    :address=>"smtp.foxmail.com",
    :port=>25,
    :domain=>"foxmail.com",
    :user_name=> "somboy",
    :password=> "123456",
    :authentication=> :login
}
  2) views\sysemail目录下建立一个发送模版sent.html.erb
    <div>
  <p>注册成功,请激活后登录</p>
  <p><h3><%=@user.name %>,您好!</h3></p>
  <p>请在浏览器的地址栏中输入如下地址来激活您的账户</p>
  <p><a href="http://localhost:3000/account/proActivate?name=<%=@user.name %

>&active_code=<%=@user.active_code %>">
    http://localhost:3000/account/proActivate?name=<%=@user.name %

>&active_code=<%=@user.active_code %>
  </a></p>
</div>
  3) app\mailers\sysemail.rb
     class Sysemail < ActionMailer::Base
  default :from => "from@example.com"

  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.sysemail.sent.subject
  #
  def sent(user,sent_at=Time.now)
    subject "激活邮件,来自【dddd】"
    recipients user.email
    from  "somboy@foxmail.com"
    sent_on sent_at
    body :user=>user
    content_type "text/html"
  end

   4) 发送的逻辑,比如保存用户后发送:
    def proReg
    @user=User.new(params[:user])
    @user.active_code=rand(Time.now.to_i).to_s
    @user.is_actived=0
    if @user.save then
      flash[:notice]="success"
      flash[:name]=@user.name
      Sysemail.deliver_sent(@user)
      render "Sysemail/sent"

20 页面缓存
  启动缓存:
   修改config/enviroments/development.rb中设置
    config.action_controller.perform_caching=true
    使用:
    cache_page :index(设置使用缓存的页面)
  清除cache
        expire_page (:action=>"index")
  局部缓存:
    <%cache do%>
        //视图中的代码
    <%end%>
     当失效时:
     expire_fragment :action=>"show"

21 分页器
   使用will_paginate库
   gem 'will_paginate','3.0.pre2'
    @tabflowers=Tabflower.paginate :page => params[:page], :per_page => 9
    sql="select count(*) from tabflowers"
    @totalTS=Tabflower.count_by_sql(sql)
    totalTS=Tabflower.count_by_sql(sql)
    @currentYS=params[:page]
    @perPage=9
    perPage=9
    if totalTS % perPage!=0
      totalJY=totalTS / perPage+1
    else
      totalJY=totalTS / perPage
    end
    @totalJY=totalJY
    @tabuser=session[:tabuser]
      respond_to do |format|
      format.html # index.html.erb
      format.xml  { renderml => @tabflowers }
    end

视图页中
      <tr><td>共<%=@totalJY %>页,共<%= @totalTS %>条,每页显示<%=@perPage %>条</td><td><%=

will_paginate @tabflowers,:prev_label=> "上一页",:next_label=>:"下一页" %></td></tr>

16 全局配置信息。比如在config目录下新建site.yml配置文件:
   title:xxxx
   author:xxxx

    在lib/enki/config.rb文件中,载入配置文件
        def self.default_location
      "#{Rails.root}/config/site.yml"
    end

  然后在app/controlers/application_controller.rb中,进行全局编码和全局变量的加载
    class ApplicationController < ActionController::Base
  protect_from_forgery
  after_filter :set_content_type

  protected

  def set_content_type
    headers['Content-Type'] ||= 'text/html; charset=utf-8'
  end

  def enki_config
    @@enki_config = Enki::Config.default
  end
  helper_method :enki_config
end  
  在前端页面中调用显示这些变量的值 <%=enki_config[:title]%>

17 content_for的用法
   如果我们想根据模板页面更改局部layout,使用content_for即可。
content_for允许模板页面代码放到layout中的任何位置。

比如我们的Rails程序不同的页面有不同的css样式,我们可以在layout里留出位置:
Java代码 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html>  
  <head>  
    <title>Todo List</title>  
    <%= stylesheet_link_tag 'application' %>  
    <%= yield :head %>  
  </head>  
  <body>  
    <div id="container">  
      <h1>Todo List</h1>  
      <%= yield %>  
    </div>  
  </body>  
</html> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Todo List</title>
    <%= stylesheet_link_tag 'application' %>
    <%= yield :head %>
  </head>
  <body>
    <div id="container">
      <h1>Todo List</h1>
      <%= yield %>
    </div>
  </body>
</html>

我们用yield :head来给模板页面某段代码留个"座位",再看页面:
Java代码 
<% content_for :head do %>  
  <%= stylesheet_link_tag 'projects' %>  
<% end %>  
<h2>Projects</h2>  
<ul>  
<% for project in @projects %>  
  <li><%= project.name %></li>  
<% end %> 

<% content_for :head do %>
  <%= stylesheet_link_tag 'projects' %>
<% end %>
<h2>Projects</h2>
<ul>
<% for project in @projects %>
  <li><%= project.name %></li>
<% end %>

content_for :head里面的代码将填充layout里的yield :head。

18 render partial参数
  
1. 默认参数

Ruby代码 
<%= render :partial => "account" %> 

<%= render :partial => "account" %>
默认本地有个变量@account, 传递过去,render到的partial(_account.erb)有个变量account

2. 单独参数 locals
locals传递一组hash参数hash 值是本地的变量,hash的key是partial里的变量

Ruby代码 
<%= render :partial => "account", :locals => { :account => @buyer } %>  
 
<% for ad in @advertisements %>  
  <%= render :partial => "ad", :locals => { :ad => ad } %>  
<% end %>  

<%= render :partial => "account", :locals => { :account => @buyer } %>

<% for ad in @advertisements %>
  <%= render :partial => "ad", :locals => { :ad => ad } %>
<% end %>
上面两个render分别
传递本地变量@buyer到_account.erb里叫account的参数
传递本地变量ad到_ad.erb里叫ad

3

根据1默认参数下面两个是一样的

Ruby代码 
<%= render :partial => "contract", :locals => { :contract  => @contract } %>  
 
<%= render :partial => "contract" %> 

<%= render :partial => "contract", :locals => { :contract  => @contract } %>

<%= render :partial => "contract" %>


4. as使用

用来改变传递之后,partial里变量的名称,如下,render方式是一样的。

Ruby代码 
<%= render :partial => "contract", :as => :agreement 
 
<%= render :partial => "contract", :locals => { :agreement => @contract } 

<%= render :partial => "contract", :as => :agreement

<%= render :partial => "contract", :locals => { :agreement => @contract }
传递@contract到_contract.erb里,partial里的变量名为agreement

5. object使用

object最简单,就是把一个变量原名传递到partial里,
所以什么都记不清楚的时候,就用object多写点都能表达

如下:
Ruby代码 
<%= render :partial => "account",bject => @buyer %>  
 
<% for ad in @advertisements %>  
  <%= render :partial => "ad",bject => ad %>  
<% end %> 

<%= render :partial => "account",bject => @buyer %>

<% for ad in @advertisements %>
  <%= render :partial => "ad",bject => ad %>
<% end %>
传递@buyer到_account.erb的partial里变量名还是@buyer
传递ad到_ad.erb的partial里变量名还是ad

6 object和as合用

Ruby代码 
<%= render :partial => "contract",bject => @contract, :as => :contract %>  
 
<%= render :partial => "contract" %> 

<%= render :partial => "contract",bject => @contract, :as => :contract %>

<%= render :partial => "contract" %>

7 collection

Ruby代码 
<%= render :partial => "ad", :collection => @advertisements %> 

<%= render :partial => "ad", :collection => @advertisements %>

@advertisements是一个array,partial里_ad.erb有个ad变量是@advertisements的成员。就是_ad.erb不用写loop只

是一条广告显示。

Ruby代码 
<%= render :partial => "ad", :collection => @advertisements, :spacer_template => "ad_divider" %> 

<%= render :partial => "ad", :collection => @advertisements, :spacer_template => "ad_divider" %>
同上,循环显示_ad.erb _ad_divider.erb 显示@advertisements.size次其中partial_ad_counter是默认计数器表示

第几条广告

8 默认

看你要partial的变量是一组记录还是一条记录,会对应约定用locals和collection
Ruby代码 
#@account是一条记录  
# <%= render :partial => "accounts/account", :locals => { :account => @account} %>  
<%= render :partial => @account %>  
 
# @posts是一组记录  
# <%= render :partial => "posts/post", :collection => @posts %>  
<%= render :partial => @posts %> 

#@account是一条记录
# <%= render :partial => "accounts/account", :locals => { :account => @account} %>
<%= render :partial => @account %>

# @posts是一组记录
# <%= render :partial => "posts/post", :collection => @posts %>
<%= render :partial => @posts %>
这是很人性的约定,可有时候就是忘了

9 一些漂亮的简写

Ruby代码 
#<%= render :partial => "account" %>可用下面代替  
<%= render "account" %>  
 
#<%= render :partial => "account", :locals => { :account => @buyer } %>可用下面代替  
<%= render "account", :account => @buyer %>  
 
# @account是一条记录  
# <%= render :partial => "accounts/account", :locals => { :account => @account } %>可用下面代替  
<%= render(@account) %>  
 
# @posts是一组记录  
# <%= render :partial => "posts/post", :collection => @posts %>可用下面代替  
<%= render(@posts) %> 

#<%= render :partial => "account" %>可用下面代替
<%= render "account" %>

#<%= render :partial => "account", :locals => { :account => @buyer } %>可用下面代替
<%= render "account", :account => @buyer %>

# @account是一条记录
# <%= render :partial => "accounts/account", :locals => { :account => @account } %>可用下面代替
<%= render(@account) %>

# @posts是一组记录
# <%= render :partial => "posts/post", :collection => @posts %>可用下面代替
<%= render(@posts) %>

10 layout

Ruby代码 
<%# app/views/users/index.html.erb &>  
Here's the administrator:  
<%= render :partial => "user", :layout => "administrator", :locals => { :user => administrator } %>  
 
Here's the editor:  
<%= render :partial => "user", :layout => "editor", :locals => { :user => editor } %>  
 
<%# app/views/users/_user.html.erb &>  
Name: <%= user.name %>  
 
<%# app/views/users/_administrator.html.erb &>  
<div id="administrator">  
  Budget: $<%= user.budget %>  
  <%= yield %>  
</div>  
 
<%# app/views/users/_editor.html.erb &>  
<div id="editor">  
  Deadline: <%= user.deadline %>  
  <%= yield %>  
</div> 
     


热点排行