49 lines
1.2 KiB
Ruby
49 lines
1.2 KiB
Ruby
|
class VotesController < ApplicationController
|
||
|
def create
|
||
|
@votable = find_votable
|
||
|
user_session = session.id
|
||
|
|
||
|
# 检查是否已经存在投票
|
||
|
existing_vote = @votable.votes.find_by(user_session: user_session)
|
||
|
|
||
|
if existing_vote
|
||
|
# 如果点击相同类型的投票,则取消
|
||
|
if existing_vote.vote_type == params[:vote_type]
|
||
|
existing_vote.destroy
|
||
|
else
|
||
|
# 否则更新投票类型
|
||
|
existing_vote.update(vote_type: params[:vote_type])
|
||
|
end
|
||
|
else
|
||
|
# 创建新投票
|
||
|
@votable.votes.create!(
|
||
|
user_session: user_session,
|
||
|
vote_type: params[:vote_type]
|
||
|
)
|
||
|
end
|
||
|
|
||
|
respond_to do |format|
|
||
|
format.turbo_stream do
|
||
|
render turbo_stream: [
|
||
|
turbo_stream.replace(
|
||
|
"#{@votable.class.name.downcase}_votes_#{@votable.id}",
|
||
|
partial: 'votes/vote_buttons',
|
||
|
locals: { votable: @votable }
|
||
|
)
|
||
|
]
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
|
||
|
private
|
||
|
|
||
|
def find_votable
|
||
|
if params[:weather_art_id]
|
||
|
WeatherArt.find(params[:weather_art_id])
|
||
|
elsif params[:city_id]
|
||
|
City.find(params[:city_id])
|
||
|
else
|
||
|
raise ActiveRecord::RecordNotFound
|
||
|
end
|
||
|
end
|
||
|
end
|