我正在使用Rails 3应用程序,该应用程序允许用户通过将电影添加到队列中来关注电影,以便在电影首映时通知他们。
由于我正在使用Mongoid,因此我对其进行了结构化,以便当用户将电影添加到其队列时,他们会创建一个嵌入式文档adds
,并且还会增加add_counter
Movie
模型由1.
我已经能够通过确认此行为在模型级别工作,但现在我正在构建控制器,我似乎无法获得通过响应。我一直在寻找一个解决方案,即使在睡觉之后再回到它,我也无法弄清楚我做错了什么。
这是我的控制器规范:
# spec/controllers/adds_controller_spec.rb
require 'spec_helper'
describe AddsController do
before(:each) do
@user = Factory(:user)
@movie = Factory(:movie)
end
describe '#create' do
context 'given valid params' do
before(:each) do
sign_in @user
end
it "creates a new add" do
add_count @user.adds.count
post :create, :movie_id => @movie.id
@user.adds.count.should == add_count + 1
end
end
end
end
这是我的控制器:
# controllers/adds_controller.rb
class AddsController < ApplicationController
before_filter :authenticate_user!
def create
@movie = Movie.find(params[:movie_id])
@user = current_user
@user.add_to_queue!(@movie)
respond_to do |format|
format.js
end
end
end
这是我的模特:
# models/movie.rb
class Movie
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
field :add_counter, :type => Integer, :default => 0
# models/user.rb
class User
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
embeds_many :adds
def add_to_queue!(movie)
if already_added?(movie) == false
adds.create!(:movie_id => movie.id)
movie.add_counter += 1
end
end
def already_added?(movie)
adds.where(:movie_id => movie.id).exists?
end
# models/add.rb
class Add
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
field :movie_id, :type => String
key :movie_id
embedded_in :user
最后,这是我运行控制器测试时来自Rspec的反馈:
Failures:
1) AddsController#create given valid params creates a new add
Failure/Error: @user.adds.count.should == 1
expected: 1
got: 0 (using ==)
# ./spec/controllers/adds_controller_spec.rb:25:in `block (4 levels) in <top (required)>'
答案 0 :(得分:1)
此代码过于复杂。我会摆脱Add类。添加的概念不应该由对象建模,而是由关系建模。
制作两个课程(简化):
<强> movie.rb 强>
class Movie
include Mongoid::Document
has_and_belongs_to_many :user_queues, :class_name => "User", :inverse_of => :movie_queue
end
<强> user.rb 强>
class User
include Mongoid::Document
has_and_belongs_to_many :movie_queue, :class_name => "Movie", :inverse_of => :user_queues
end
这里的语法可能并不完全,但将它们视为数组,你会变得很好。