2009年7月25日土曜日

[Rails][習作] 簡易ブックマークアプリ (2)

前回作成したscaffoldに、タグの表示と編集機能を追加します。

タグ表示

indexページの一覧表示テーブルに、タグを表示する列を追加します。ついでにブックマーク先へのリンクも追加。
# app/view/bookmarks/index.html.erb
<h1>Listing bookmarks</h1>

<table border="1">
<tr>
<th>Url</th>
<th>Comment</th>
<th>Tag</th>
</tr>

<% @bookmarks.each do |bookmark| %>
<tr>
<td><%=link_to bookmark.url, bookmark.url %></td>
<td><%=h bookmark.comment %></td>
<td>
<% bookmark.tags.each do |tag| %>
[<%= tag.tag %>]
<% end %>
</td>
<td><%= link_to 'Show', bookmark %></td>
<td><%= link_to 'Edit', edit_bookmark_path(bookmark) %></td>
<td><%= link_to 'Destroy', bookmark, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />

<%= link_to 'New bookmark', new_bookmark_path %>

一覧画面にTagが表示されるようになります。



タグ編集

ブックマーク新規追加画面で、タグを追加できるように修正します。
app/view/bookmarks/new.html.erb に、以下を追加。

<!-- タグ追加用テキストフィールド -->
<p>
<%= f.label 'Tag' %><br />
<%= text_field_tag 'tags', '', :size=>30 %>
</p>


これで新規作成画面に、タグ編集用のテキストフィールドが追加されます。
コントローラ側では、createアクションを次のように修正。パラメータ"tags"で渡された文字列をスペースで分割し、分割したトークンそれぞれをタグとして登録しています。

# app/controllers/bookmarks_controller.rb
def create
@bookmark = Bookmark.new(params[:bookmark])

success = @bookmark.save
# add tags
params[:tags].split(/\s/).each do |tag|
t = Tag.new(:tag=>tag)
success = t.save
@bookmark.tags << t
end
respond_to do |format|
if success
flash[:notice] = 'Bookmark was successfully created.'
format.html { redirect_to(@bookmark) }
format.xml { render :xml => @bookmark, :status => :created,:location => @bookmark }
else
format.html { render :action => "new" }
format.xml { render :xml => @bookmark.errors, :status =>:unprocessable_entity }
end
end
end


ブックマーク編集画面も、同様に修正していきます。

まず現在のタグを編集用のビューに渡す必要があるので、editアクションを次のように修正します。

# app/controllers/bookmarks_controller.rb
def edit
@bookmark = Bookmark.find(params[:id])
# タグを連結した文字列をビューに渡す
@tags = ""
@bookmark.tags.each do |tag|
@tags.concat "#{tag.tag} "
end
@tags.sub! /\s$/, ""
end


ビュー側(app/view/bookmarks/edit.html.erb)では、タグ編集用テキストフィールドを用意して、インスタンス変数 tags を初期値に設定します。

<!-- タグ編集用テキストフィールド -->
<p>
<%= f.label 'Tag' %><br />
<%= text_field_tag 'tags', @tags, :size=>30 %>
</p>


ブックマーク編集画面に、タグ編集用フィールドが追加されます。



そして、コントローラのupdateアクションに、createアクションと同様にタグの処理を追加します。現在登録されているタグをすべて削除した後、あらためてタグの追加を行います。

# app/controllers/bookmark_controller.rb
def update
@bookmark = Bookmark.find(params[:id])
# clear Tags
@bookmark.tags.clear

respond_to do |format|
success = @bookmark.update_attributes(params[:bookmark])
# add tags
params[:tags].split(/\s/).each do |tag|
t = Tag.new(:tag=>tag)
success = t.save
@bookmark.tags << t
end
if success
flash[:notice] = 'Bookmark was successfully updated.'
format.html { redirect_to(@bookmark) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @bookmark.errors, :status=>:unprocessable_entity }
end
end
end


以上で、タグの追加・編集ができるようになりました。

------
<< [Rails][習作] 簡易ブックマークアプリ (1)    [Rails][習作] 簡易ブックマークアプリ (3) >>

0 件のコメント:

コメントを投稿