ROR里的查找主要使用find命令:
先贴一段API
find
(*args)
Find operates with four different retrieval approaches:
- Find by id
- This can either be a specific
id
(1), a list of ids (1, 5, 6), or an
array of ids ([5, 6, 10]). If no record can be found for all
of the listed ids, then RecordNotFound
will be raised.
- Find first
- This will return the first
record matched by the options used.
These options can either be specific conditions or merely an order. If no
record can be matched, nil
is returned. Use Model.find(:first
, *args)
or its shortcut
Model.first(*args)
.
- Find last
- This will return the last
record matched by the options used. These
options can either be specific conditions or merely an order. If no record
can be matched, nil
is returned. Use Model.find(:last
, *args)
or its shortcut
Model.last(*args)
.
- Find all
- This will return all
the records matched by the options used.
If no records are found, an empty array is returned. Use Model.find(:all
, *args)
or its shortcut
Model.all(*args)
.
All approaches accept an options hash
as
their last
parameter.
Parameters
-
:conditions
- An SQL fragment like "administrator = 1",
[ "user_name = ?", username ]
, or ["user_name =
:user_name", { :user_name => user_name }]
. See conditions in
the intro.
-
:order
- An SQL fragment like "created_at DESC, name".
-
:group
- An attribute name by which the result should be grouped.
Uses the GROUP BY
SQL-clause.
-
:having
- Combined with +:group+ this can be used to filter the
records that a GROUP BY
returns. Uses the HAVING
SQL-clause.
-
:limit
- An integer determining the limit on the number of rows
that should be returned.
-
:offset
- An integer determining the offset from where the rows
should be fetched. So at 5, it would skip rows 0 through 4.
-
:joins
- Either an SQL fragment for additional joins like
"LEFT JOIN comments ON comments.post_id = id
" (rarely needed), named associations
in the same form used for the :include
option, which will perform
an INNER JOIN
on the associated table(s), or an array containing a
mixture of both strings and named associations. If the value is a string,
then the records will be returned read-only since they will have attributes
that do not correspond to the
table‘s columns
. Pass :readonly
=> false
to override.
-
:include
- Names associations that should be loaded alongside. The
symbols named refer to already defined associations. See eager loading
under Associations.
-
:select
- By default, this is "*" as in "SELECT *
FROM", but can be changed if you, for example, want to do a join but
not include the joined columns
. Takes a
string with the SELECT SQL fragment (e.g. "id
, name").
-
:from
- By default, this is the table name of the class, but can
be changed to an alternate table name (or even the name of a database
view).
-
:readonly
- Mark the returned records read-only so they cannot be
saved or updated.
-
:lock
- An SQL fragment like "FOR UPDATE" or "LOCK
IN SHARE MODE". :lock => true
gives connection
‘s default exclusive lock,
usually "FOR UPDATE".
Examples
# find by id
Person.find(1) # returns the object for ID = 1
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
Person.find([1]) # returns an array for the object with ID = 1
Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
Note that returned records may not be in the same order as the ids you
provide since database rows are unordered. Give an explicit :order
to ensure the results are sorted.
Examples
# find first
Person.find(:first) # returns the first object fetched by SELECT * FROM people
Person.find(:first, :conditions => [ "user_name = ?", user_name])
Person.find(:first, :conditions => [ "user_name = :u", { :u => user_name }])
Person.find(:first, :order => "created_on DESC", :offset => 5)
# find last
Person.find(:last) # returns the last object fetched by SELECT * FROM people
Person.find(:last, :conditions => [ "user_name = ?", user_name])
Person.find(:last, :order => "created_on DESC", :offset => 5)
# find all
Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
Person.find(:all, :offset => 10, :limit => 10)
Person.find(:all, :include => [ :account, :friends ])
Person.find(:all, :group => "category")
Example for find
with a lock: Imagine two
concurrent transactions: each will read person.visits == 2
, add 1
to it, and save
, resulting in two saves of
person.visits = 3
. By locking the row, the second transaction has
to wait until the first
is finished; we get
the expected person.visits == 4
.
Person.transaction do
person = Person.find(1, :lock => true)
person.visits += 1
person.save!
end
然后介绍另外一些常见的查询:
1.关联查询
@goods = Good.find(:all,
:conditions =>["goods.id=?",params[:id]],
:include => [:user])
http://hideto.iteye.com/blog/105774
还可以查看这个网址
分享到:
相关推荐
在处理Oracle数据库查询时,ActiveRecord的查询接口使得SQL操作变得简单,如`.find`, `.where`, `.all`等。 部署是另一个关键环节。确保服务器环境也安装了必要的依赖,并正确配置了Oracle数据库连接。Rails应用...
@user = User.find_by(email: "john@example.com") ``` 更新用户信息: ```ruby @user.update(name: "Jane Doe") ``` 删除用户: ```ruby @user.destroy ``` 六、使用压缩包中的资源 "multiple_sqlite"这个...
如代码所示,我们先设定开始和结束日期,然后根据`params[:id]`获取员工ID,通过`Employee`模型的`find_with_timesheets_in_date_range`方法查询数据。 在`Employee`模型中,`find_with_timesheets_in_date_range`...
1. **参数化查询**:ActiveRecord的查询接口使用方法链,如`find_by`,`where`等,它们会自动处理SQL注入。你应该避免使用字符串拼接构建查询。 2. **白名单参数**:对用户输入进行验证,只允许特定格式的数据。 3...
在IT行业中,尤其是在Java开发领域,我们经常遇到各种运行时异常。"Nacos启动异常"是一个常见的问题,这里出现的具体异常是`java.lang.UnsatisfiedLinkError`,它通常发生在试图加载本地(C/C++)库时找不到相应的库...
template_for_shower 使用 Express 4 的 Node.js 应用程序,用于使用 Shower ( ) 构建演示文稿 在本地运行 确保您已安装 git clone ... cd template_for_shower npm install npm start 您的应用程序现在应该在上...
4. **循环右移指令(ROR)**:在指定范围内循环右移数值。 ### 数据选择与比较指令 1. **选择指令(SEL)**:根据条件选择两个数值中的一个。 2. **最大值指令(MAX)**:返回两个数值中的最大值。 3. **最小值...
TBL_FIND(Table Find表格查找)**: 表查找。用于在指定的表格中查找特定的数据项。 #### 八、数据转换指令 **64. BCD_I(Binary Coded Decimal_I二进制编码的十进制)**: BCD码转整数。用于将BCD编码转换为整数格式...
- **循环指令**:如ROL(循环左移)和ROR(循环右移)。 - **移位指令**:如SFTL(左移)和SFTR(右移)。 - **位处理指令**:如BIT_SET(置位)。 - **数据处理指令**:如ADD(加法)。 - **结构体创建指令**:如...
20.1.5 改进的findBy 245 20.2 对插件系统的改进 245 20.3 数据绑定 245 20.4 在GSP中使用JSP的标签 246 20.5 加密配置文件中的数据库密码 246 20.6 本章小结 246 参考文献 247 索引 248 Grails技术精解与Web...
- `find_all`: 查找所有符合条件的元素。 - `grep`: 匹配元素。 - `include?`: 包含元素。 - `max`: 获取最大值。 - `min`: 获取最小值。 - `reject`: 拒绝符合条件的元素。 - `sort`: 排序元素。 #### 三、...
**PowerPro** 的外部指令主要由不同的库提供,这些指令能够实现更高级的功能,如字符串处理、位操作、版本信息查询等。 ##### 1. 字符串处理指令 - **结合字符串指令 (CONCAT)**:连接两个或多个字符串。 - **删除...
- **移位和循环移位指令**:如SHL(左移),SHR(右移),ROL(循环左移),ROR(循环右移)。 2. **置位域/复位域指令**: - S指令用于置位,将指定的地址范围设为1。 - R指令用于复位,将指定的地址范围设为0...
例如,`Book.find_by(title: '某书名')`会查找标题为指定值的书籍。 9. ** erb模板** ERB(Embedded Ruby)是Rails视图中常用的模板引擎,可以插入Ruby代码到HTML中。例如,`<%= @book.title %>`会显示书籍的标题...
[3078995] ROL/ROR/SHL/SHR modeling wrong when dest reg is 32 bit [2864794] BX_INSTR_OPCODE in "cpu_loop" causes crash in x86_64 host [2884071] [AIX host] prefetch: EIP [00010000] > CS.limit [0000...
RCR 6.6.3.3 - ROL 6.6.3.4 - ROR 6.6.4 - The Bit Operations 6.6.4.1 - TEST 6.6.4.2 - The Bit Test Instructions: BT, BTS, BTR, and BTC 6.6.4.3 - Bit Scanning: BSF and BSR 6.6.5 - ...