現在以下のエラーで詰まっております。尚、favariteのスペルは誤字となります。
ActionController::UrlGenerationError
実際に指摘をされている箇所
No route matches {:action=>"destroy", :blog_id=>#<Blog id: 7, user_id: 2, title: "aaa", body: "aaaa", image_id: "9006d95ab6ed9a6c4dd1879a726a47d24dbfde03cb40daae57...", created_at: "2021-08-30 07:53:35", updated_at: "2021-08-30 07:53:35">, :controller=>"favarites"}, missing required keys: [:id]
### controller
def create
@favatrite = current_user.favarites.create(blog_id: params[:blog_id])
redirect_back(fallback_location: root_path)
end
def destroy
@blog = Blog.find(params[:blog_id])
@favatrite = current_user.favarites.find_by(blog_id: @blog.id)
@favatrite.destroy
redirect_back(fallback_location: root_path)
end
routes.rb
devise_for :users
root to: "home#index"
resources :users
resources :blogs do
resources :favarites, only: [:create, :destroy]
resources :comments, only: [:create,:destroy]
collection do
get 'search'
end
end
favarite model
class Favarite < ApplicationRecord
belongs_to :user
belongs_to :blog
varidates_uniqueness_of :blog_id, scope: :user_id
end
blogs_controller
def index
@blogs = Blog.order(id: "DESC")
end
### user model
class User < ApplicationRecord
has_many :blogs, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :favarites, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
attachment :profile_image
validates :username, presence: true def already_favarited?(blog) self.favarites.exists?(blog_id: blog.id) end
end
rails routes
blog_favarites POST /blogs/:blog_id/favarites(.:format) favarites#create
blog_favarite DELETE /blogs/:blog_id/favarites/:id(.:format) favarites#destroy
blog:index.heml.erb
<div class = "container"> <% @blogs.each do |blog|%> <%= link_to blog_path(blog) do %> <%= attachment_image_tag blog, :image %><br> <% end %> <%= link_to user_path(blog.user.id) do %><br> <%= attachment_image_tag blog.user, :profile_image ,fallback: "no-image.png" %><br> <% end %> <%= link_to blog.user.username,user_path(blog.user.id) %><br> <%= blog.updated_at.strftime("%Y-%m-%d %H:%M") %>更新<br><% if current_user.already_favarited?(blog) %>
<%= link_to blog_favarite_path(blog), method: :delete do %>
<i class="fas fa-heart"></i>
<% end %>
<% else %>
<%= link_to blog_favarites_path(blog), method: :post do %>
<i class="far fa-heart"></i>
<% end %>
<%= blog.favarites.count %>
<% end %>
<% end %>
blogの中にkeyも入っているのとrouteもおかしくはないと思ったのですが、どうすれば解決に至るのでしょうか?
お分かりの方がいらしたらご教授のほどよろしくお願いいたします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/08/31 07:05
2021/08/31 07:09