エラー
1) Error: UsersProfileTest#test_profile_display: ActionView::Template::Error: undefined method `like?' for nil:NilClass app/views/users/_like_form.html.erb:2 app/views/microposts/_micropost.html.erb:9 app/views/users/show.html.erb:19 test/integration/users_profile_test.rb:11:in `block in <class:UsersProfileTest>'
このエラーでAjaxが機能しないと思うのですが。
ActionController::UnknownFormat (ActionController::UnknownFormat): app/controllers/favorites_controller.rb:7:in `create'
app/views/users/_like_form.html.erb
rb
1<div id="like_form"> 2 <% if current_user.like?(micropost) %> 3 <%= render 'favorites/unlike', micropost: micropost %> 4 <% else %> 5 <%= render 'favorites/like', micropost: micropost %> 6 <% end %> 7</div>
app/views/favorites/_unlike.html.erb
html
1<%= button_to favorite_path(micropost), method: :delete, remote: true do %> 2 <%= micropost.liked.count %> 3 <span style = "color:red;">♡</span> 4<% end %>
app/views/favorites/_like.html.erb
html
1<%= button_to favorites_path(micropost), method: :post, remote: true do %> 2 <%= micropost.liked.count %> 3 <span >♡</span> 4<% end %>
app/controllers/favorites_controller.rb
rb
1before_action :logged_in_user, only: [:create, :destroy] 2 3 def create 4 @micropost = Micropost.find_by(id: params[:format]) 5 current_user.like(@micropost) 6 respond_to do |format| 7 format.html { redirect_to request.referer } 8 format.js 9 end 10 end 11 12 def destroy 13 @micropost = Micropost.find_by(id: params[:id]) 14 current_user.unlike(@micropost) 15 respond_to do |format| 16 format.html { redirect_to request.referer } 17 format.js 18 end 19 end 20end
app/models/user.rb
rb
1. 2. 3. 4 # いいねする 5 def like(other_micropost) 6 likes << other_micropost 7 end 8 9 # いいね解除 10 def unlike(other_micropost) 11 favorites.find_by(micropost_id: other_micropost.id).destroy 12 end 13 14 # いいねしているか? 15 def like?(other_micropost) 16 likes.include?(other_micropost) 17 end 18. 19. 20.
app/views/favorites/create.js.erb
js
1$("#like_form").html("<%= escape_javascript(render(partial: 'favorites/unlike', locals: { micropost: @micropost })) %>");
app/views/favorites/destroy.js.erb
js
1$("#like_form").html("<%= escape_javascript(render(partial: 'favorites/like', locals: { micropost: @micropost })) %>");
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/03/30 10:30 編集
2022/03/30 10:56
2022/03/30 13:05 編集