LoginSignup
0
0

More than 3 years have passed since last update.

rails 基本その3 投稿画面の作成

Last updated at Posted at 2019-11-06

その10,投稿画面の作成(ルーティング)

routes
  get 'home/new' => 'home#new'
  #投稿画面のルーティング
  post 'home' => 'home#create'
  #データベースへの登録のルーティング

その11, 投稿画面の作成(コントローラー)

controlloer
   def new
   end
   # 投稿画面

  def create
    テーブル名.create(カラム名: params[:カラム名(ビューのid)],他に投稿内容があれば繰り返し・・・)
  end
   #これでビューで入れられた内容からデータベースに入れることができる。

 #例
 def create
  Item.create(name: params[:name], image: params[:image], text: params[:text])
 end


controlloer
   #セキュリティーのためストロングパラメーターの設定の場合
   def new
      parameter = test_params
    end
    #privateで設定して変数を持ってくる

    private
    def test_params
      params.permit(:キー名(カラム名), 同文・・・)
    end

    #例
    def create
      Item.create(tweet_params)
    end

    private
    def tweet_params
      params.permit(:name, :image, :text)
    end
    #これでセキュリティが付加されて記述された。

その12, 投稿画面と投稿完了画面の作成(ビューの作成例)

ビュー(new.html.erb)
<!--基本form_tagを作成しメソッドをpostに指定-->  
<!--input.textareaなどを打ち込んで,nameで入れたいカラムを指定-->  
 
 <div>
  <%= form_tag('/home', method: :post) do %>
    <h3>
      サンプルフォーム
    </h3>
    <div>
      <label>Name:</label>
      <input palceholder="Name" type="text" name="name">
    </div>
    <div>
      <label>text</label>
      <textarea name="text" placeholder="text"></textarea>
    </div>
    <div>
      <label>image</label>
      <input placeholder="image" type="text" name="image">
    </div>
    <div>
      <input type="submit">
    </div>
  <% end %>
</div>

ビュー(create.html.erb)
  #投稿が完了したこのページに遷移
 
  <div class="contents row">
    <div class="success">
      <h3>
        投稿が完了しました。
      </h3>
      <a class="btn" href="/tweets">投稿一覧へ戻る</a>
    </div>
  </div>

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