LoginSignup
0
0

More than 1 year has passed since last update.

ユーザーと記事を紐付け④

Posted at

author_name のリファクタリング

筆者の名前を動的に表示するようにしていきます。

app/views/articles/show.html.haml
にて、
 - if @article.user.present?
 - としており、ユーザーが存在していれば書く。存在していなければ書かないとなる。

しかし、前回の設定で、データーベースとスキーマを変更して、絶対にユーザーが存在するようにしているので、

上記の行を消す。

app/views/articles/_article.html.haml
こちらも同じif文を消す。

%p= article.user.display_name
これが長いので、変更する!

%p= article.author_name

で表示されるようにする。

app/models/article.rb
今アーティクルはユーザーと紐づいている。
まずは、ユーザーをとり、ユーザーにはディスプレイネームというメソッドがあるので、こうなる。

def author_name
    user.display_name
end

app/views/articles/show.html.haml
app/views/articles/_article.html.haml
ともに、

%p= article.author_name

にしておく!

※リファクタリングとは、ソフトウェアの外部的振る舞いを保ちつつ、理解や修正が簡単になるように、内部構造を改善することです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0