Guest User

Untitled

a guest
Feb 21st, 2018
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. Database tables look like so:
  2.  
  3. items:
  4. +----+---------
  5. | id | title
  6. +----+---------
  7. | 1 | Test 1
  8. | 2 | Test 2
  9.  
  10. tags:
  11. +----+---------+
  12. | id | tag |
  13. +----+---------+
  14. | 1 | tag1 |
  15. | 2 | tag2 |
  16.  
  17. items_tags:
  18. +----+---------+--------+
  19. | id | item_id | tag_id |
  20. +----+---------+--------+
  21. | 1 | 1 | 1 |
  22. | 2 | 2 | 2 |
  23.  
  24.  
  25. Models look like:
  26.  
  27. models/item.rb
  28. class Item < ActiveRecord::Base
  29. has_and_belongs_to_many :tags
  30.  
  31. def tags_s=(tags_s)
  32. for tag in tags_s.split(' ')
  33. self.tags.push(Tag.find_or_create_by_tag(tag))
  34. end
  35. end
  36.  
  37. def tags_s
  38. tags.join(' ')
  39. end
  40. end
  41.  
  42. models/tag.rb
  43. class Tag < ActiveRecord::Base
  44. has_and_belongs_to_many :items
  45.  
  46. def to_s
  47. return tag
  48. end
  49. end
  50.  
  51.  
  52. On the console this happens:
  53. >> newitem = Item.new
  54. => #<Item:0xb750ba74 @new_record=true, @attributes={"created_on"=>nil, "text"=>nil, "title"=>"", "updated_on"=>nil, "type"=>""}>
  55. >> newitem.title = "console test"
  56. => "console test"
  57. >> newitem.text = "test"
  58. => "test"
  59. >> newitem.save
  60. => true
  61. >> newitem
  62. => #<Item:0xb750ba74 @new_record=false, @new_record_before_save=true, @attributes={"created_on"=>Sun Nov 26 18:21:09 GMT 2006, "text"=>"test", "title"=>"console test", "updated_on"=>Sun Nov 26 18:21:09 GMT 2006, "type"=>"", "id"=>3}, @errors=#<ActiveRecord::Errors:0xb75067a4 @base=#<Item:0xb750ba74 ...>, @errors={}>>
  63. >> newitem.tags_s=("tag2")
  64. ActiveRecord::StatementInvalid: Mysql::Error: Duplicate entry '2' for key 1: INSERT INTO items_tags (`item_id`, `tag_id`, `id`) VALUES (3, 2, 2)
  65. .... trace snipped ...
  66. >> newitem.tags_s=("tag3")
  67. => "tag3"
  68.  
  69. That is, if the tag doesn't exist then this works fine, if it exists then for some reason it tries to add an entry to the join table with an id that already exists (looks like the id of the first entry which references the required tag). Why does it do this? It doesn't need to save an id at all as the database will generate it automatically. How can I fix it?
Add Comment
Please, Sign In to add comment