Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I'm trying to create a song with associated tags, but my create method throws an error:

Tag(#70267554396440) expected, got String(#70267493763880)

My Songs#create:

def create
 tags = params[:song][:tag_list].split(", ")
 @song = current_user.songs.create(song_params)
 tags.each do |tag| 
   if Tag.find_by(:name => tag)
       @song.tags << tag
   else 
     @song.tags.create(:name => tag)
   end
 end
 flash[:success] = "You have successfully created a new track!"
 redirect_to @song
end

What should I do? The issue seems to be with adding an existing tag to the song.

share|improve this question

2 Answers 2

You could also potentially simplify your code using the find_or_create_by method:

@song.tags << Tag.find_or_create_by(:name => tag.name)

Check out this link for some documentation.

share|improve this answer

We need to find the the tag, and then set it in a variable to call it.

tags.each do |tag_name| 
  if t = Tag.find_by(:name => tag_name)
    @song.tags << t
  else 
    @song.tags.create(:name => tag_name)
  end
end
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.