一、session中来自model的危险
在session中存model的时候需要谨慎些,有时候它会变得很不听话而且特尼玛容易和数据库不同步,所以最好的方式不是存model在session中,而是存model的ID,并从数据库中根据ID来抓model
- class UsersController < ApplicationController
- def prepare
- session[:user] = User.find(:user)
- redirect_to action: 'show'
- end
- def show
- @user = session[:user]
- end
- def update
- @user = session[:user]
- @user.name = "Foo"
- redirect_to action: 'show'
- end
- end
科学的写法应该是这个样子滴
- class UsersController < ApplicationController
- def prepare
- session[:user_id] = User.find(:user).id
- redirect_to action: 'show'
- end
- def show
- @user = User.find(session[:user_id])
- end
- def update
- @user = User.find(session[:user_id])
- @user.name = "Foo"
- redirect_to action: 'show'
- end
- end
二、在model中执行计算
你知道吗,其实在model中,ActiveRecord提供了类方法来计算一些东西,这些继承自ActiveRecord的方法甚至能让你在关联的时候使用
打开console(话说Ruby2.0开启console的速度杠杠的,童鞋快去down下来试试吧)
- >>Task.find(:first).priority
- =>4
- >>Task.sum(:priority)
- =>15
- >>Task.sum(:priority, conditions: 'complete=0')
- =>13
- >>Task.maximum(:priority)
- =>4
- >>Task.minimum(:priority)
- =>1
- >>Task.average(:priority)
- =>2.5
三、有趣的find条件
你能传给condition可不仅仅是简单的string,数组、排序还有nil空值都能传。
其中的“?”是占位符,有点像c中print函数的%d
- >>Task.count(:all, conditions: ["complete=? and priority=?", false, 3])
- =>2
- >>Task.count(:all, conditions: ["complete=? and priority=?", false, nil])
- =>0
- >>Task.count(:all, conditions: ["complete=? and priority IS ?", false, nil])
- =>0
- >>Task.count(:all, conditions: ["complete=? and priority IS ?", false, [1,3])#This not right
- <pre name="code" class="ruby">>>Task.count(:all, conditions: ["complete=? and priority IN (?)", false, [1,3])
- =>1</pre>
- <pre></pre>
- 犹豫ruby的特性,上面的等价于下面这个<pre name="code" class="ruby">>>Task.count(:all, conditions: ["complete=? and priority IN (?)", false, 1...3)
- =>1</pre>
- <pre></pre>
- <pre></pre>
除了形如
- ["complete=? and priority IN (?)", false, 1...3)
的查询语句,你可以采用ruby强横的hash句式来查询
- >>Task.count(:all, conditions: { complete: false, priority: 1})
四、虚拟属性
虚拟属性是一个很有意思的东西,它显得很灵活,比如像这样一个表单:
这是符合我们的数据库的,因为数据库中的User所具有的column就是first_name和last_name,但在现实中我们何曾把名和姓分开呢?我们当然会希望这个样子:
对应的erb是
问题来了,我们的User Model以及数据表中可是没有full_name的,你这是要逆天吗?当然不是,我们自己来定义一个就好了:
通过join方法我们连full_name也可以直接取了,而full_name=(name)方法则把上面那个erb中的full_name给分而化之了,这样就不会在往数据库存的时候出现意外了
- <h1>Register</h1>
- <% form_for(@user), url: users_path do |f| %>
- <p>
- Full name</br>
- <%= f.text_field :full_name%>
- </P>
- <p>
- Password</br>
- <%= f.password_field :password%>
- </P>
- <p>
- <%= submit_tag 'Register'%>
- </P>
- <% end %>
- class User < ActiveRecord::Base
- attr_accessible :first_name, :last_name, :password
- def full_name
- [first_name, last_name].join(' ')
- end
- def full_name=(name)
- split = name.split(' ',2)
- self.first_name = split.first
- self.last_name = split.last
- end
- end