- 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.
50 lines
1.5 KiB
JavaScript
50 lines
1.5 KiB
JavaScript
import { Controller } from "@hotwired/stimulus"
|
|
|
|
export default class extends Controller {
|
|
connect() {
|
|
this.setupVoteButtons()
|
|
}
|
|
|
|
setupVoteButtons() {
|
|
document.querySelectorAll('.vote-btn').forEach(button => {
|
|
button.addEventListener('click', this.handleVote.bind(this))
|
|
})
|
|
}
|
|
|
|
async handleVote(event) {
|
|
const button = event.currentTarget
|
|
const votableType = button.dataset.votableType
|
|
const votableId = button.dataset.votableId
|
|
const action = button.dataset.action
|
|
|
|
try {
|
|
const response = await fetch('/votes', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
|
|
},
|
|
body: JSON.stringify({
|
|
votable_type: votableType,
|
|
votable_id: votableId,
|
|
vote_type: action
|
|
})
|
|
})
|
|
|
|
const data = await response.json()
|
|
|
|
if (data.success) {
|
|
this.updateVoteCounts(data)
|
|
} else {
|
|
alert(data.message)
|
|
}
|
|
} catch (error) {
|
|
console.error('Vote error:', error)
|
|
}
|
|
}
|
|
|
|
updateVoteCounts(data) {
|
|
document.getElementById('upvotes-count').textContent = data.upvotes
|
|
document.getElementById('downvotes-count').textContent = data.downvotes
|
|
}
|
|
}
|