22
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby on Rails ~お気に入り登録(ブックマーク)機能の実装(コードメモ)

Last updated at Posted at 2016-12-31

◆イベント一覧から興味のあるイベントをお気に入り登録する機能!
すでに「favorite」というテーブルを作成していたため、
今回はお気に入り登録に使うテーブルは「clip」とする。

#1.モデルの作成。

$ bundle exec rails g model clips

生成されるファイル...

      invoke  active_record
      create    db/migrate/20161231060901_create_clips.rb
      create    app/models/clip.rb
      invoke    test_unit
      create      test/models/clip_test.rb
      create      test/fixtures/clips.yml

#2.アソシエーションの設定

app/models/clip.rb
class Clip < ActiveRecord::Base
    belongs_to :user
    belongs_to :event
end
app/models/event.rb
class Event < ActiveRecord::Base
    has_many :clips
    has_many :users, through: :clips
end
app/models/user.rb
class User < ActiveRecord::Base
    has_many :clips, dependent: :destroy #この行を追記することで関連付くイベントが削除されるとclipも削除されます。
    has_many :events, through: :clips
end

#3.マイグレーションファイルの編集

db/migrate/...
class CreateClips < ActiveRecord::Migration
  def change
    create_table :clips do |t|
      t.references :user, null:false
      t.references :event, null:false
      t.timestamps null: false
    end

    add_index :clips, :user_id
    add_index :clips, :event_id
  end
end

#4.テーブルの生成

$ bundle exec rake db:migrate

#5.routesの設定

config/routes.rb
  resources :events do
    member do
      post "add", to: "clips#create"
    end
  end

  resources :clips, only: [:destroy]

#6.コントローラーの作成

$ bundle exec rails g controller clips

#7.コントローラーの編集

app/controllers/clips_controller.rb
class ClipsController < ApplicationController
  def create


    @user_id = current_user.id
    @event_id = Event.find(params[:id]).id
    @clip = Clip.new(event_id: @event_id, user_id: @user_id)


      if @clip.save
        redirect_to user_path(current_user)
      end

  end

  def destroy
    @clip = Clip.find(params[:id])
    if @clip.destroy
      redirect_to user_path(current_user)
    end
  end

end

#8.viewの編集

app/views/events/show.html.erb
      <div>
      <%= link_to "このイベントをクリップ", add_event_path(event), method: :post %>
      </div>
22
29
1

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
22
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?