Agile Web Development with Rails 读书笔记 (二)

昨天在调试的过程中还是比较顺利,但是在开发上由于没有使用集成的开发环境,整体来说开发的比较慢,一会用命令行建立数据库,一会又要启动服务器,一会又要用编辑文件,窗口开了一大堆,感觉很不舒服。

ROR的安装包里边带的编辑器SciTE还是不错的,但是只是一个编辑器而已,谈不上集成的开发环境,所以今天主要的工作是找一个比较好一些的集成开发环境,浪费了一些时间。

最开始的时候用的是VIM,虽然配置成功也使用了几个必须的插件,但是使用起来还是十分的别扭,操作国语复杂,而且最要命的是需要记一大堆的命令,后来选择了RadRails这个开发工具,目前感觉还是不错的,因此强烈建议新手首先要使用这个工具,效果还是不错的,大家可以从网上下载一些模板,使用起来就更方面了。ReadRails的配置和注意事项,网上已经有几篇不错的文章了,大家可以Google一下。

今天剩下的时间就是完成第6章剩余部分的代码了,大致内容如下:

修改模块product.rb

class Product < ActiveRecord::Base
  
#判断指定的字段是否为空
  validates_presence_of :title,:description,:img_url
  
#判断指定字段价格是否为数字
  validates_numericality_of :price    
  
#判断书的标题是否为唯一值  
  validates_uniqueness_of :title
  
#判断img_url格式是否合法
  validates_format_of :img_url,:with => %r{^http:.+\.(gif|jpg|png)$}i,
                      
:message => "must be a URL for a GIF,JPG, or PNG image." 
  
#validate函数会在Product实例前自动调用
  def validate
    
#判断是否为正数
    errors.add(:price,"should be positive"unless price.nil? || price >= 0.01
  end
end

其中Ruby的语法可以在http://rubycn.ce-lab.net上进行查看,感觉语法还是很好理解,就是还不太习惯,总是需要查看手册。

修改视图 list.rhtml

<h1>Listing products</h1>

<table cellpadding="5" cellspacing="0">
<%
odd_or_even 
= 0
for product in @products
  odd_or_even 
= 1 - odd_or_even
%>
  
<tr valign="top" class="ListLine<%= odd_or_even %>">
    
<td>
        
<img width="60" heithg="70" src="<%= product.img_url%>">
    
</td>
    
<td width="60%">
        
<span class="ListTitle">
            
<%= h(product.title) %></br>
            
<%= h(truncate(product.description,80)) %>
        
</span>
    
</td>
    
<td aligh="right">
        
<%= product.date_available.strftime("%y-%m-%d"%></br>
        
<strong><%= sprintf("%0.2f",product.price )%></strong>            
    
</td>
    
<td class="ListActions">
    
<%= link_to 'Show', :action => 'show', :id => product %><br/>
    <%= link_to 'Edit', :action => 'edit', :id => product %><br/>
    <%= link_to 'Destroy', { :action => 'destroy', :id => product }, :confirm => 'Are you sure?', :method => :post %>
    </td>
  
</tr>
<end %>
</table>

<%= link_to 'Previous page', { :page => @product_pages.current.previous } if @product_pages.current.previous %>
<%= link_to 'Next page', { :page => @product_pages.current.next } if @product_pages.current.next %> 

<br />

<%= link_to 'New product', :action => 'new' %>

其中一些语句如h函数、truncate、sprintf、date_available.strftime等,还是经常要用到的。

最后是修改样式表scaffold.css添加如下代码

.ListTitle{
  color
:#244;
  font-weight
:bold;
  font-size
:larger;
  
}

.ListActions
{
  font-size
:x-small;
  text-align
:right;
  padding-left
:lem;
 
}
 
.ListLine0
{
  background
:#e0f8f8;
}

.ListLine1
{
  background
:#f8b0f8;
}

循序渐进的来吧,先有一个好的开发环境,在加快学习吧,但是有一点要注意,有了这个工具,也许就不太愿意记忆ROR的命令了,这个可不行哦,还是记忆一下的好。
原文地址:https://www.cnblogs.com/Duiker/p/674681.html