LoginSignup
0
0

More than 3 years have passed since last update.

コントローラーの@の使い方

Last updated at Posted at 2020-03-07

【例】モデル名がpostのとき

app/controllers/posts_controller.rb
class TweetsController < ApplicationController

 def index
    @posts = Post.includes(:user)
  end

  def new
    @post = Post.new
  end

  def create
    Post.create(post_params)
  end
〜以下略〜
end

があるとします。
モデルクラス名はPost先頭大文字・単数系です。
@postで@はほかのファイルにも使えます。postはposts_controller.rb内でしか処理できません。
【例】

 <%= simple_format(@post.text) %>
    <span class="XXXX">
    <a href="/users/<%= @post.user.id %>">
      <span>投稿者</span><%= @post.user.nickname %>
      </a>
    </span>
  </div>
  <div class="YYYY">
    <% if current_user %>
      <%= form_with(to_model: [@post, @comment], local: true) do |form| %>
        <%= form.text_area :text, placeholder: "コメント", rows: "2" %>
        <%= form.submit "送信" %>
      <% end %>
    <% else %>
      <strong><p>*** コメント投稿には新規登録またはログインが必要 ***</p></strong>
    <% end %>

上記のように@であれば使うことができます。

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