0

So I have the same action for all intents and purposes being executed. Yet one work and the other does not.

DB setup

add_column :cards, :score, :integer, :default => 0
add_column :cards, :comments, :integer, :default => 0

=> Card(id: integer, user_id: integer, event: text, created_at: datetime, updated_at: datetime, score: integer, comments: integer)

The vote controller (this one works)

  def create
@vote = Vote.where(:card_id => params[:vote][:card_id], :user_id => current_user.id).first
if @vote
  @vote.up = params[:vote][:up]
  @vote.save
  @card = Card.find(params[:vote][:card_id])
  if @vote.up == true
    @card.score += 2
  else
    @card.score -= 2
  end
  @card.save
else
  @vote = Vote.new
  @vote.card_id = params[:vote][:card_id]
  @vote.user = current_user
  @vote.up = params[:vote][:up]
  @vote.save
  @card = Card.find(params[:vote][:card_id])
  if @vote.up == true
    @card.score += 1
  else
    @card.score -= 1
  end
  @card.save
end
redirect_to :back
end

comments controller (does not work) i get "no implicit conversion of Fixnum into Array"

def create
  @comment = Comment.new
  @comment.message = params[:comment][:message]
  @comment.card_id = params[:comment][:card_id]
  @comment.user = current_user
  @comment.save
  @card = Card.find(params[:comment][:card_id])
  @card.comments += 1
  @card.save
  redirect_to :back
end

What am I missing here? Thank you all for your help in advance.

Ian

2 Answers 2

4

I'm guessing you also have an association between Cards and Comments, eg. Card has_many :comments. Your @card.comments method is now ambiguous - are you referring to the association or the value of the integer? Rails is assuming the association, but you wanted the integer.

For something like this, I suggest looking into counter caches: http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference (section 4.1.2.3). This involves adding a comments_count field to your Card model, and counter_cache: true to the association from Comments to Cards. Rails will then maintain the count for you automatically.

Sign up to request clarification or add additional context in comments.

Comments

0

@sevenseacat That did it. I posted the question before bed, and thought of exactly that when I was trying to fall asleep. I figured it could not be that. Thank you for confirming my thoughts and getting me to try it. I'm looking into the counter caches thank you for the point in a a better direction.

Ian

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.