- Create VotesController to manage voting actions - Implement Vote model with polymorphic associations - Add vote buttons to the city and weather art views - Integrate vote counting and user vote tracking - Define routes for the votes resource This commit sets up a voting mechanism for cities and weather arts, allowing users to upvote or downvote. It includes seamless integration of user sessions to track individual votes, ensuring votes can be modified or deleted based on user interaction.
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 |