lundi 2 novembre 2015

Cannot save record to database RAILS nested forms

I cannot seem to save my record with nested forms.

This is what pry says:

pry(#<VenuesController>)> @venue.save
   (0.3ms)  begin transaction
  Tag Exists (0.2ms)  SELECT  1 AS one FROM "tags" WHERE ("tags"."name" = 'All ' AND "tags"."id" != 2) LIMIT 1
  Tag Exists (0.1ms)  SELECT  1 AS one FROM "tags" WHERE "tags"."name" = '' LIMIT 1
   (0.1ms)  rollback transaction
=> false

I thought I followed everything correctly. This is my nested form for tags

Tags:
    <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name %><br>

  Make a New Tag Here: <br>

   <%= f.fields_for :tags, Tag.new do |tag_field| %>
    <%= tag_field.label :name_tag %>
    <%= tag_field.text_field :name %>
    <% end %>

This is my venue model

class Venue < ActiveRecord::Base
  has_many :venue_tags
  has_many :tags, :through => :venue_tags

  accepts_nested_attributes_for :tags, allow_destroy: true
end

And my tag model

class Tag < ActiveRecord::Base
  has_many :venue_tags
  has_many :venues, :through => :venue_tags

  validates_uniqueness_of :name
end

However, when take off the 'validate uniqueness of name', I can save it, but new tags are added by itself.

And this is the pry log that tells it's true, but now I'm getting the correct tag added to the venue, but ALSO a new tag added to the venue (one I did not create myself). I am assuming this is happening because the New Tag Fields_for text was blank, which created a new tag by itself.

(0.2ms)  begin transaction
  SQL (0.6ms)  INSERT INTO "venues" ("name", "address", "discount", "latitude", "longitude", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["name", "SPICEBOX"], ["address", "33 Pell St, New York, NY 10013, United States"], ["discount", "10% OFF with Student ID"], ["latitude", 40.714831], ["longitude", -73.998628], ["created_at", "2015-11-03 06:12:52.400643"], ["updated_at", "2015-11-03 06:12:52.400643"]]
  SQL (0.2ms)  INSERT INTO "venue_tags" ("tag_id", "venue_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["tag_id", 2], ["venue_id", 11], ["created_at", "2015-11-03 06:12:52.404715"], ["updated_at", "2015-11-03 06:12:52.404715"]]
  SQL (0.2ms)  INSERT INTO "tags" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", ""], ["created_at", "2015-11-03 06:12:52.408821"], ["updated_at", "2015-11-03 06:12:52.408821"]]
  SQL (0.1ms)  INSERT INTO "venue_tags" ("venue_id", "tag_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["venue_id", 11], ["tag_id", 9], ["created_at", "2015-11-03 06:12:52.411692"], ["updated_at", "2015-11-03 06:12:52.411692"]]
   (1.4ms)  commit transaction
=> true

Aucun commentaire:

Enregistrer un commentaire