I am setting up a website for categories and topics and messages with votes from users for each category, topic, and message. Here I am trying to create a new vote object, and the error is NoMethodError (undefined method 'category_id' for #ActiveRecord::Relation[]), for vote. I find this strange because most errors with ActiveRecord::Relation objects involve Vote.where or Vote.find_by, whereas here I am just trying to reference a new or created object, vote.
Here is the code in my controller, and I will add more code if needed.
def create
@vote = Vote.new(vote_params)
@vote.user_id = current_user.id
category = @category
topic = @topic
message = @message
if category != nil && topic === nil && message === nil then
@vote.category_id = category.id
if @vote === Vote.find_by(user_id: current_user.id, category_id: category.id) then
flash[:notice] = "You have already voted."
elsif @vote != Vote.find_by(user_id: current_user.id, category_id: category.id) then
@vote.save!
flash[:notice] = "Thankyou for voting."
redirect_to categories_path(category_id: category.id)
end
elsif category != nil && topic != nil && message === nil then
@vote.category_id = category.id
@vote.topic_id = topic.id
if @vote === Vote.find_by(user_id: current_user.id, category_id: category.id, topic_id: topic.id) then
flash[:notice] = "You have already voted."
elsif @vote != Vote.find_by(user_id: current_user.id, category_id: category.id, topic_id: topic.id) then
@vote.save!
flash[:notice] = "Thank you for voting."
redirect_to category_topics_path(category_id: category.id, topic_id: topic.id)
end
elsif message != nil then
@vote.category_id = message.category_id
@vote.topic_id = message.topic_id
@vote.message_id = message.id
if @vote === Vote.find_by(user_id: current_user.id, category_id: category.id, topic_id: topic.id, message_id: message.id)
flash[:notice]= "You have already voted."
elsif @vote != Vote.find_by(user_id: current_user.id, category_id: category.id, topic_id: topic.id, message_id: message.id)
@vote.save!
flash[:notice] = "Thank you for voting."
redirect_to category_topic_messages_path(category_id: category.id, topic_id: topic.id, message_id: message.id)
end
end
end
Aucun commentaire:
Enregistrer un commentaire