CRUDを追加しよう

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(中垣健志)

CRUDを追加しよう

web2pyはまた、フォームをさらに単純化するCRUD(Create/Read/Update/Delete)APIを提供します。CRUDを使用するには、"db.py"ファイルなど、どこかにそれを定義する必要があります:

web2py also provides a CRUD (Create/Read/Update/Delete) API that simplifies forms even more. To use CRUD it is necessary to define it somewhere, such as in file "db.py":

1.

2.

from gluon.tools import Crud

crud = Crud(globals(), db)

これら2つの行は、すでに雛形アプリケーションに含まれています。

These two lines are already in the scaffolding application.

crudオブジェクトは高レベルのメソッドを提供します。例えば:

The crud object provides high-level methods, for example:

1.

form = crud.create(table)

これは、次のプログラミング・パターンを置き換えるために使用することができます:

that can be used to replace the programming pattern:

1.

2.

3.

4.

form = SQLFORM(table)

if form.accepts(request.post_vars,session):

session.flash = '...'

redirect('...')

前回の"show"アクションを、crudを用いてより改良して書き換えてみます:

Here, we rewrite the previous "show" action using crud and making some more improvements:

1.

2.

3.

4.

5.

6.

7.

8.

def show():

image = db.image(request.args(0)) or redirect(URL('index'))

db.comment.image_id.default = image.id

form = crud.create(db.comment,

message='your comment is posted',

next=URL(args=image.id))

comments = db(db.comment.image_id==image.id).select()

return dict(image=image, comments=comments, form=form)

初めに、次のような構文を用いていることに注意してください

First of all notice we have used the syntax

1.

db.image(request.args(0)) or redirect(...)

これにより、要求されたレコードが取り出されます。table(id)は、レコードが見つからない場合にNoneを返します。したがって、or redirect(...)を同じ行に書くようにします。

to fetch the required record. Since table(id) returns None if the record is not found, we can use or redirect(...) in this case in one line.

crud.createのnext引数は、フォームが受理された後にリダイレクトする先のURLです。message引数は受理されたときに表示されるものです。CRUDについては第7章でより詳しく説明します。

The next argument of crud.create is the URL to redirect to after the form is accepted. Themessage argument is the one to be displayed upon acceptance. You can read more about CRUD in Chapter 7.