TodoList: 公開先変更の解説 ― 2006年12月21日 10時10分34秒
先ず、app/controllers/todo_controller.rb に @published_organizations = TodoOrganizationPermission.find(:all, :conditions=>["todo_id=?", params[:id]])
を入れた。app/views/todo/show.rhtml から、@published_organizations にアクセス出来る。
show.rhtml に <%= @published_organizations.inspect %>
を加えて、表示した。表示結果は、
[#"1", "published"=>"1", "id"=>"1", "organization_id"=>"1"}>,
#"1", "published"=>"1", "id"=>"2", "organization_id"=>"2"}>,
#"1", "published"=>"0", "id"=>"3", "organization_id"=>"4"}>]
SQL の結果が配列として返ってくるのを確認した。なお、find() に :all を与えると、SQL に適合する項目が何も無かったときに、空の配列が返ってくる。
組織 (Organization) を全て表示し、この SQL の結果を使って、公開情報を求めればよい。最初に、テーブルを表示するときの定石を scaffold によって作られた show.rhtml に加える。
<table>
<tr>
<% for column in Organization.content_columns %>
<th><%= column.human_name %></th>
<% end %>
<th>Published-to</th>
</tr>
<% for org in @organizations %>
<tr>
<% for column in Organization.content_columns %>
<td><%= org.send(column.name) %></td>
<% end %>
</tr>
<% end %>
</table>
次は、ループの中で、各 org の公開情報を点検するだけだ。ループの中で、毎回 @published_organizations の配列を解析するのは、効率の面でも良くない。そこで、組織 (Organization) の id のみを取り出す。@organization_ids = @published_organizations.map { |o| o.organization_id }
を app/controllers/todo_controller.rb の show 関数に追加した。<%= @organization_ids.inspect %>
を app/views/todo/show.rhtrml に追加すると、[1, 2, 4]
が表示されるようになった。
次の段階は、実際にループの中でこれらの値を得ることだ。
<table>
<tr>
<% for column in Organization.content_columns %>
<th><%= column.human_name %></th>
<% end %>
<th>Published-to</th>
</tr>
<% for org in @organizations %>
<tr>
<% for column in Organization.content_columns %>
<td><%= org.send(column.name) %></td>
<% end %>
<td><%= if @organization_ids.member?(org.id) then "YES"
else "NO" end %></td>
</tr>
<% end %>
</table>
@organization_ids.member?(org.id)
で [1, 2, 4]
の中に現在の所属団体 (Organization) があるかを調べられる。
しかし、それだけでは充分ではない。一度、公開した後に、公開を中止することが出来る。Array.index() を使って、値を調べる。<%= if @organization_ids.member?(org.id) && @published_organizations[@organization_ids.index(org.id)]['published'] != 0 then "YES" else "NO" end %>
がその部分にあたる。
後は、実験用に埋め込んだコードを消すだけだ。
最近のコメント