【发布时间】:2014-04-26 23:42:54
【问题描述】:
我有一个简单的测试:
it "should create a post through a user for a blog." do
@user.blogs.create(title: @blog.title)
@user.blogs.find_by_title(@blog.title).posts.create(title: 'some title')
post = Post.find_by_title('some title')
post.title.should == 'some title'
end
这失败了。为什么?因为我们没有任何用户博客。好的,让我们在他们的:
it "should create a post through a user for a blog." do
@user.blogs.create(title: @blog.title)
binding.pry
@user.blogs.find_by_title(@blog.title).posts.create(title: 'some title')
post = Post.find_by_title('some title')
post.title.should == 'some title'
end
现在在控制台中,让我们看看@user.blogs 是否给了我们任何东西。
@user.blogs
=> [#<Blog id: nil, title: "user_blog_26">]
好的....但这不是整个命令。让我们看看@blogs 有没有什么。
@blog
=> #<Blog id: 26, title: "user_blog_26">
好的,我们得到了一些结果,我们看到@user 与他们关联了相同的博客。 (虽然@user.blogs中缺少id……(注意:用户与博客的关系为:User has_and_belongs_to_many :blogs, join_table: 'blogs_users')
那么让我们做吧:
@user.blogs.find_by(title: @blog.title)
=> nil
嗯.....
怎么了?
- 一个:我的用户博客关联没有 id。
- 二:@user.blogs,返回该用户的所有博客,但@user.blogs.find_by(title: @blog.title) 返回nil?哦哦
怎么了?
额外的信息,以获得乐趣
模型
class User < ActiveRecord::Base
include Promiscuous::Subscriber
subscribe :first_name, :email, :user_name, :last_name
has_and_belongs_to_many :blogs, join_table: 'blogs_users'
has_many :posts, through: :blogs
validates :first_name, presence: true
validates :email, presence: true, uniqueness: true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
class Blog < ActiveRecord::Base
has_many :posts
validates :title, presence: true, uniqueness: true
end
【问题讨论】:
-
尝试使用
.build而不是.create
标签: ruby-on-rails rspec entity-relationship relationship models