使用Rails 4.1.13和Ruby 2.0.0(雖然我有與Ralis 4.0和Ruby 1.9.3相同的問題。問題,並不明白爲什麼我的解決方案(這看起來像this完全一樣)不起作用,所以請幫我。Rails has_many通過無法保存在嵌套的形式由於id = null
我有兩個模型BlogPost和標籤。一個BlogPost可以有很多標籤和一個標籤可以有很多BlogPosts。我連他們通過第三個模型BlogPostRelation因此,這是我的基本設置:
# blog_post.rb
has_many :blog_post_tag_relations, dependent: :destroy
has_many :tags, :through => :blog_post_tag_relations
accepts_nested_attributes_for :blog_post_tag_relations, :tags
# tag.rb
has_many :blog_post_tag_relations, dependent: :destroy
has_many :blog_posts, :through => :blog_post_tag_relations
# blog_post_tag_relation.rb
belongs_to :tag
belongs_to :blog_post
validates_uniqueness_of :tag_id, :scope => [:blog_post_id]
validates :blog_post_id, :presence => true
validates :tag_id, :presence => true
accepts_nested_attributes_for :tag, :blog_post
我有博文形式,使用Formtas抽動,其中I創建使用用於博客帖子複選框:
<%= f.input :blog_title %>
<%= f.input :tags, as: :check_boxes, :collection => tags.order(:name) %>
我是,標籤被添加之前其導致不存在blog_post_id的驗證失敗(它是不是)博文未保存的問題:
Tag Load (1.6ms) SELECT "tags".* FROM "tags" WHERE "tags"."id" IN (678, 56)
(0.9ms) BEGIN
BlogPost Exists (1.6ms) SELECT 1 AS one FROM "blog_posts" WHERE ("blog_posts"."id" IS NOT NULL) AND "blog_posts"."slug" = 'de22323' LIMIT 1
BlogPostTagRelation Exists (1.2ms) SELECT 1 AS one FROM "blog_post_tag_relations" WHERE ("blog_post_tag_relations"."tag_id" = 678 AND "blog_post_tag_relations"."blog_post_id" IS NULL) LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "blog_posts" WHERE ("blog_posts"."id" IS NOT NULL) AND "blog_posts"."slug" = 'de22323' LIMIT 1
BlogPostTagRelation Exists (1.1ms) SELECT 1 AS one FROM "blog_post_tag_relations" WHERE ("blog_post_tag_relations"."tag_id" = 56 AND "blog_post_tag_relations"."blog_post_id" IS NULL) LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "blog_posts" WHERE ("blog_posts"."id" IS NOT NULL) AND "blog_posts"."slug" = 'de22323' LIMIT 1
(0.8ms) ROLLBACK
這似乎是解決方案應該是使用inverse_of
,我坦率地不明白100%。還應該提及的是,我不是100%確定如何使用accepts_nested_attributes_for
來解決這類問題。我已經嘗試了所有不同的設置,但據我瞭解只有他們應該待的地方是在連接模式,BlogPostRelation,像這樣:
# blog_post_tag_relation.rb
belongs_to :tag, :inverse_of => :blog_post_tag_relations
belongs_to :blog_post, :inverse_of => :blog_post_tag_relations
validates_uniqueness_of :tag_id, :scope => [:blog_post_id]
validates :blog_post_id, :presence => true
validates :tag_id, :presence => true
accepts_nested_attributes_for :tag, :blog_post
這不工作,要麼,我完全在現在失去了去做。
- 最重要:我該怎麼辦?
- 是否解決這個問題的inverse_of?如果是這樣,我該如何使用它?
- 我是否正確使用accep_nested_attributes_for?
- 是否有BlogPostTagRelation的命名做(如果它被稱爲BlogPostTag呢?
我知道這很簡單!謝謝 – Christoffer
呃,這是我學到的教訓,幾乎是以同樣的方式:) –