LoginSignup
2
1

More than 5 years have passed since last update.

本当の初心者のためのemunを使った状態管理(クリック一つで状態変遷させるやつ)の実装 rails

Last updated at Posted at 2017-09-26

親切なコメントを受けて修正しました。
コメントまたは下記のリンクから詳しい説明と動画付きのページに飛べます。
https://qiita.com/jnchito/items/c7e93c7a1fc7fc34a177

以下から本文(上記のリンクで十二分なので見る必要はないかもしれない)

参考 https://qiita.com/shizuma/items/d133b18f8093df1e9b70

前半部分の話は上記が詳しくてわかりやすいです。

ですが本当の初心者(僕を含めて)はroute や controller や view 周りなどはこれを見ただけは実装するのが難しいです。(簡単??)

ちなみに下記はinteger型の実装例です。

controller

article controller

app/controllers/hoges_controller.rb

  def toggle_status
    if @article.draft?
      @article.published!
    elsif @article.published?
      @article.draft!
    end

    redirect_to "wherever you like"
  end

みたいな感じでcontrollerを定義する

route

app/config/routes.rb
修正前
get :toggle_status
修正後
patch :toggle_status

みたいな感じでrouteを設定する

view

app/views/articles/hoge.html.erb
修正前
<%= link_to article.status, toggle_status_article_path(article) %>
修正後
<%= link_to article.status, toggle_status_article_path(article),method: :patch %>

みたいな感じで程よい場所に設置する

結論

一応これでボタン一つで状態を変遷させるやつが実装できます。

初心者はview controller model route 全て具体例がないと実装できません(泣)
そのようなクソ雑魚ナメクジも世の中には存在することを頭の片隅に置いて投稿してくれる人が増えれば幸いです。

2
1
2

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