这可能是基本的东西,但我确实做了我的作业。我仍然无法找到解决方案。
我有一个用户数据库,一个电影数据库和一个评级数据库。评分有movie_id,user_id和评分。
class Rating < ActiveRecord::Base
attr_accessible :grade
belongs_to :user
belongs_to :movie
end
class User < ActiveRecord::Base
has_many :ratings, :dependent => :destroy
has_many :movies, :through => :ratings
...
class Movie < ActiveRecord::Base
has_many :ratings, :dependent => :destroy
has_many :users, :through => :ratings
...
但我无法使用movie_id和user_id
创建评分rails c test
Loading test environment (Rails 3.0.3)
@movie=Factory(:movie)
#<Movie id: 1, title: "Rocky 20", link: "#", created_at: "2011-01-22 21:04:42", updated_at: "2011-01-22 21:04:42">
@user=Factory(:user)
#<User id: 1, name: "lola", email: "lola@gmail.com", created_at: "2011-01-22 21:04:48", updated_at: "2011-01-22 21:04:48", encrypted_password: "c306a696138fa08c543ada3a3b4fd92067e9941743b7558e891...", salt: "f82c6abaccec17e2866d50150ad200181eb4bc8e0204249f171...", admin: false>
>> @user.ratings.create(:grade=> 4, :movie_id =>@movie.id)
=> #<Rating id: 1, grade: 4, user_id: nil, movie_id: nil, created_at: "2011-01-22 21:04:55", updated_at: "2011-01-22 21:04:55">
“movie_id:nil”就是杀了我......
当然我测试没有通过: @ user.rating.create(grade =&gt; 5,:movie_id =&gt; @ movie.id)没有movie_id @ movie.rating.create(grade =&gt; 5,:user_id =&gt; @ user.id)没有user_id
任何提示?
谢谢!
答案 0 :(得分:0)
你在这里展示的代码应该绝对适用于IMO。这让我觉得这是你没有在这里展示的东西。我尝试了几件事:
我已经尝试了你的例子,这就是我得到的:
> m = Movie.create :title => "Foo"
=> #<Movie id: 1, title: "Foo", created_at: …>
> u = User.create :name => "Marc"
=> #<User id: 1, name: "Marc", created_at: …>
> u.ratings.create :grade => 4, :movie_id => m.id
=> #<Rating id: 1, grade: 4, user_id: 1, movie_id: 1, created_at: …>
> m.ratings.create :grade => 3, :user_id => u.id
=> #<Rating id: 2, grade: 3, user_id: 1, movie_id: 1, created_at: …>
您也可以这样使用,如您所知:
> m.ratings.create :grade => 3, :user => u
=> #<Rating id: 3, grade: 3, user_id: 1, movie_id: 1, created_at: …>
答案 1 :(得分:0)
尝试像这样定义你的工厂:
Factory.define :movie, :class => Movie do |f|
f.title "Rocky 20"
f.link "#"
end
Factory.define :user, :class => User do |f|
f.name "Lola"
f.email "lola@gmail.com"
end
Factory.define :rating, :class => Rating do |f|
f.movie { |m| m.association :movie}
f.user { |u| u.association :user}
f.grade 4
end
然后测试评级,单独使用评级工厂:
it "creates a rating" do
rating = Factory.create(:rating)
rating.user.name.should == "Lola"
rating.movie.title.should == "Rocky 20"
end