記事のビュー更新 (ユーザ権限): 小林研 Rails Tips (81)

このページの内容は以下のリポジトリに1日遅れで反映されます(記事執筆前に前日分をコミットしています)。

https://github.com/hkob/hkob_blog

はじめに

Rails Tips の 81 回目です。昨日までに所有しないオブジェクトに対する対応が終わりました。実際にはこれらの所有しないオブジェクトに対しては、ビューでそのようなリンクが発生しないようにするべきです。今回は、所有しないオブジェクトに対する編集や削除のリンクを発生させないよにします。

Rails をはじめよう - Railsガイド

index.html.haml

まず、記事の執筆者を列に追加しています。また、edit と destroy のリンクの前に owned_by? で権限を確認しています。

- content_for :title do
  - @page_title = t ".title"

%table
  %thead
    = labels Article, %w[title user_name], add_control: true
  %tbody
    - @articles.each do |article|
      - next if article.archived?

      %tr
        %td= article.title
        %td= article.user_name
        %td
          = lotfp article_path(article)
          - if article.owned_by? current_user
            = lotfp edit_article_path(article)
            = destroy_lotfp article_path(article), Article
    %tr
      %td= lotfp new_article_path

user_name の翻訳テキストはまだ用意していないので、models/ja.yml の attributes に追加しておきまする

    attributes:
      article:
        title: タイトル
        body: 本文
        user_name: 執筆者
        created_at: 作成日時
        updated_at: 更新日時

あとは、show.html.haml についても同様に修正しました。

- content_for :title do
  - @page_title = @article.title

%p= @article.body

- if @article.owned_by? current_user
  %ul
    %li= lotfp edit_article_path(@article)
    %li= destroy_lotfp article_path(@article), Article

%h2 Comments
= render partial: "articles/comments/comment", collection: @comments

- if @comment.new_record?
  %h2 Add a comment:
  = render "articles/comments/form"

おわりに

これで記事に関するユーザ関係の処理を行いました。次にコメントにもユーザを追加してみたいと思います。