お世話になっております。
現在Railsの勉強を パーフェクト RubyonRailsという書籍を使って勉強をしております。
その書籍を勉強中にどうしてもうまくいかない部分があったので、質問させてください。
ページ数でいうと、 6章の320ページで、イベントシステムの詳細ページにイベントを作ったユーザーがアクセスした際に編集ボタンを表示するという部分になります。
[システム概要]
ユーザーが イベント情報を投稿できるシステム
モデルのコード下記に、created_by?のメソッドを作成しました。
event.rb
1class Event < ApplicationRecord 2 belongs_to :owner, class_name: "User" 3 4 validates :name, length: {maximum: 50}, presence: true 5 validates :place, length: {maximum: 100}, presence: true 6 validates :content, length: {maximum: 2000}, presence: true 7 validates :start_at, presence: true 8 validates :end_at, presence: true 9 validates :start_at_should_be_before_end_at 10 11 12 def created_by?(user) 13 return false unless user 14 15 owner_id == user.id 16 end 17 18 private 19 def start_at_should_be_before_end_at 20 return unless start_at && end_at 21 22 if start_at >= end_at 23 errors.add(:start_at, "は終了時間よりも前に設定してください") 24 end 25 end 26end 27
events/show.html.haml
1%h1.mt-3.mb-3= @event.name 2.row 3 .col-8 4 .card.mb-2 5 %h5.card-header イベント内容 6 .card-body 7 %p.card-text= @event.content 8 .card.mb-2 9 %h5.card-header 開催時間 10 .card-body 11 %p.card-text= "#{l(@event.start_at, format: :long)} - #{l(@event.end_at, format: :long)}" 12 .card.mb-2 13 %h5.card-header 開催場所 14 .card-body 15 %p.card-text= @event.place 16 .card.mb-2 17 %h5.card-header 主催者 18 .card-body 19 = link_to("https://github.com/#{@event.owner.name}", class: "card-link") do 20 = image_tag @event.owner.image_url, width: 50, height: 50 21 = "@#{@event.owner.name}" 22 .col-4 23 - if @event.created_by?(current_user) < --------- ここでevent.rbで定義したメソッドを使いたい. 24 = link_to("イベントを編集する", edit_event_path(@event), class: "btn btn-info btn-lg btn-block") 25 26 -# - if @event.owner.id == current_user.id 27 = link_to("イベントを編集する", edit_event_path(@event), class: "btn btn-info btn-lg btn-block") 28
上記のコードで bin/rails s をして、作成したイベントの詳細にアクセスすると、
NoMethodError in Events#show
となり、
といったエラーになってしまいます.
[ためしたこと]
dbを一度作り直したり..してみたのですが、ダメでした。
よろしくお願いいたします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/01/23 12:23
2022/01/23 21:02
2022/01/24 10:45