Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 加入模型创建测试失败,因为它缺少相关模型,不确定原因?_Ruby On Rails_Rspec - Fatal编程技术网

Ruby on rails 加入模型创建测试失败,因为它缺少相关模型,不确定原因?

Ruby on rails 加入模型创建测试失败,因为它缺少相关模型,不确定原因?,ruby-on-rails,rspec,Ruby On Rails,Rspec,以下是失败的测试: before(:each) do @attr = { :user_id => "1", :project_id => "1", :owner_type => "client" } end it "should create a new instance given valid attributes" do Ownership.create!(@attr) end 以下是失败的

以下是失败的测试:

before(:each) do
    @attr = { 
      :user_id => "1", 
      :project_id => "1",
      :owner_type => "client"
    }
  end

  it "should create a new instance given valid attributes" do
     Ownership.create!(@attr)
   end
以下是失败的原因:

Failures:

  1) Ownership should create a new instance given valid attributes
     Failure/Error: Ownership.create!(@attr)
     ActiveRecord::RecordInvalid:
       Validation failed: User can't be blank, Project can't be blank
     # ./spec/models/ownership_spec.rb:14:in `block (2 levels) in <top (required)>'
以下是我的用户模型:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :admin, :projects

  has_many :ownerships
  has_many :projects, :through => :ownerships

  accepts_nested_attributes_for :projects
class用户:所有权
接受以下项目的\u嵌套\u属性\u

问题是否可能是因为您将字符串而不是整数传递给
用户id
项目id
的值?

添加
:用户id
:项目id
属性
。就像您为
:owner\u type
所做的那样。所以看起来应该是这样的

attr_accessible :owner_type, :user_id, :project_id

这应该可以解决问题。

不,我现在意识到我的所有权根本没有被创造出来,不知道为什么。下面是我用来在用户和项目之间创建新所有权的方法:current_user.ownerships.create(:owner_type=>'designer',:project=>@project),虽然有效,但在实际应用程序中没有正确创建所有权。我在原来的问题中添加了更多的信息。任何你想指定为属性的东西,甚至关系,都需要在attr_下可访问。比如:project,:user等。查看我的所有权模型…我的attr_中确实有可访问的属性..但是通过我在问题中列出的方法设置它不起作用。哦,等等…你是说我需要我的所有权模型的attr_中的:user和:project?但是…当我做用户项目时,它就起作用了
class User < ActiveRecord::Base
  attr_accessible :name, :email, :admin, :projects

  has_many :ownerships
  has_many :projects, :through => :ownerships

  accepts_nested_attributes_for :projects
attr_accessible :owner_type, :user_id, :project_id