LoginSignup
1
0

More than 3 years have passed since last update.

ruby構文における変数 @有無

Last updated at Posted at 2021-01-26

目的

・ruby構文における@の使用方法について理解を深める

内容

下記のindex.html.erbとshow.html.erbを比較するとリストタグ内

 <%= link_to '編集', edit_tweet_path(@tweet.id), method: :get %>
index.html.erb
edit_tweet_path(tweet.id)
show.html.erb
edit_tweet_path(@tweet.id)

となっているが、indexとshowで@の有無の違いが生じるのは何故でしょうか。
どちらもコントローラーでは@tweet(もしくは@tweets)に値を代入しているので、HTML.erbで使用する際は@が必要と思われるが、どうしてindexに@が無いのかと疑問に思いませんか。
内容を深掘りしていきましょう。

〜記〜

index.html.erb
<div class="contents row">
  <% @tweets.each do |tweet| %>
    <div class="content_post" style="background-image: url(<%= tweet.image %>);">
      <div class="more">
        <span><%= image_tag 'arrow_top.png' %></span>
        <ul class="more_list">
          <li>
            <%= link_to '詳細', tweet_path(tweet.id), method: :get %>
          </li>
          <li>
            <%= link_to '編集', edit_tweet_path(tweet.id), method: :get %>
          </li>
          <li>
            <%= link_to '削除', tweet_path(tweet.id), method: :delete %>
          </li>
        </ul>
      </div>
      <p><%= tweet.text %></p>
      <span class="name">
        <%= tweet.name %>
      </span>
    </div>
  <% end %>
</div>
show.html.erb
<div class="contents row">
  <div class="content_post" style="background-image: url(<%= @tweet.image %>);">
    <div class="more">
      <span><%= image_tag 'arrow_top.png' %></span>
      <ul class="more_list">
        <li>
          <%= link_to '編集', edit_tweet_path(@tweet.id), method: :get %>
        </li>
        <li>
          <%= link_to '削除', tweet_path(@tweet.id), method: :delete %>
        </li>
      </ul>
    </div>
    <p><%= @tweet.text %></p>
    <span class="name"><%= @tweet.name %>
    </span>
  </div>
</div>
tweets_controller.rb
class TweetsController < ApplicationController

  def index
    @tweets = Tweet.all
  end

  def new
    @tweet = Tweet.new
  end

  def create
    Tweet.create(tweet_params)
  end

  def destroy
    tweet = Tweet.find(params[:id])
    tweet.destroy
  end

  def edit
    @tweet = Tweet.find(params[:id])
  end

  def update
    tweet = Tweet.find(params[:id])
    tweet.update(tweet_params)
  end

  def show
    @tweet = Tweet.find(params[:id])
  end

  private

  def tweet_params
    params.require(:tweet).permit(:name, :image, :text)
  end
end

答え

index.html.erbの2行目に注目すると

index.html.erb
@tweets.each do |tweet|

というeach構文があリます。
ここでは@tweetsというインスタンス変数をtweetという変数に置き換えている処理が行われています。
つまり、indexの2行目で@tweetsはtweetという変数に置き換わるため、以降はtweetをもいて、コードを組み立てる必要があるため、indexではtweetを使っているのです。
@tweet=tweetsのように分かりやすい形では無いが、eachメソッドで値が変換されることについては意外と謳われていないのでは無いでしょうか?

備忘録として残しておきます。

1
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
1
0