1
我有模型用戶,最喜歡的,孩子和媽媽。如何改進代碼以切換遠程按鈕之間的狀態?
class User < ActiveRecord::Base
has_many :kids
has_many :favorites
def favorited?(mom)
favorites.where(mom_id: mom.id).any?
end
end
class Mom < ActiveRecord::Base
has_many :kids
has_many :favorites
end
class Kid < ActiveRecord::Base
belongs_to :user
belongs_to :mom
end
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :mom
end
我列出了一羣孩子爲一個用戶,並允許用戶在孩子們的列表裏面最喜歡的媽媽。
class KidsController < ApplicationController
before_action :authenticate_user!
index
@kids = Kid.paginate(:page => params[:page])
end
end
class FavoritesController < ApplicationController
before_action :authenticate_user!
respond_to :js, :json, :html
def create
@mom = Mom.find(params[:id])
@favorite = current_user.favorites.build(params[:favorites])
@favorite.mom_id = @mom.id
@favorite.save
if request.xhr?
head :ok
else
redirect_to :back
end
end
def destroy
@favorite = current_user.favorites.find(params[:id])
@favorite.destroy
end
end
孩子/指數
- @kids.each do |kid|
- if current_user.favorited?(kid.mom)
%li
= link_to({ controller: "favorites", action: "destroy", id: current_user.favorites.find_by(mom_id: kid.mom.id).id }, { method: :delete, remote: true }, data: { toggle_text: 'Favorite', toggle_href: { controller: 'favorites', action: 'create', id: kid.mom.id }}) do
%i.fa.fa-star-o.fa-fw
Unfavorite
- else
%li
= link_to({ controller: 'favorites', action: 'create', id: kid.mom.id }, { method: :post, remote: true }, data: { toggle_text: 'Unfavorite', toggle_href: { controller: "favorites", action: "destroy", id: current_user.favorites.find_by(mom_id: kid.mom.id) } }) do
%i.fa.fa-star.fa-fw
Favorite
我不能得到這個正常工作,我猜是因爲我怎麼有我的鏈接設置它。或者它可能是別的。我不知道替代方法做到這一點,所以我在這裏尋求幫助。我需要在代碼中更改什麼,以便我可以切換鏈接的不同狀態,並通過Ajax讓它不受歡迎和喜愛?