试图通过accepts_nested_attributes_for来find_or_create?

时间:2011-12-08 20:13:35

标签: ruby-on-rails ruby-on-rails-3 postgresql activerecord ruby-on-rails-3.1

我正在尝试find_or_create通过accepts_nested_attributes_for接受的相关模型。

我有一个Trip模型

class Trip < ActiveRecord::Base
  attr_accessible :organiser_attributes

  accepts_nested_attributes_for :organiser
  belongs_to :organiser, class_name: 'GuestUser', :autosave => true
end

如您所见,每次旅行都属于GuestUser,他们被称为组织者。

class GuestUser < ActiveRecord::Base
  attr_accessible :name, :email, :phone

  has_many :trips, foreign_key: :organiser_id
end

现在我对GuestUser的电子邮件有一个唯一性约束(在验证和数据库级别)。因此,如果GuestUser创建了2次旅行,我希望将第二次旅行应用于同一个GuestUser记录。

我发现this questions似乎描述了实现这一目标的方法。但是,我似乎无法使其发挥作用。

在我的Trip模型中,我添加了:

class Trip < ActiveRecord::Base
  #other stuff ...

  belongs_to :organiser, class_name: 'GuestUser', autosave: true

  def autosave_associated_records_for_organiser
    # Find or create the organiser by name
    if new_organiser = GuestUser.find_by_email(organiser.email) then
      self.organiser = new_organiser
    else
      self.organiser.save!
    end
  end
end

described in the docs。但是这个测试:

describe TripsController do
  describe "POST create success" do
    before :each do
      @guest_user = Factory.attributes_for(:guest_user)
      @trip = Factory.attributes_for(:trip)
      @valid_attr = @trip.merge(organiser_attributes: @guest_user)
    end

    describe "if the guest user already exists" do
      it "should still create a trip" do
        GuestUser.create! @guest_user
        expect do
          post :create, trip: @valid_attr, format: :json
        end.to change(Trip, :count).by(1)
      end
    end
  end
end

失败并显示以下消息:

Failures:
  1) TripsController POST create success if the guset user already exists should still create a trip
      Failure/Error: expect do
        count should have been changed by 1, but was changed by 0
      # ./spec/controllers/trips_controller_spec.rb:26:in `block (4 levels) in <top (required)>'

这是测试日志:

  Processing by TripsController#create as JSON
  Parameters: {"trip"=>{"price"=>"3456", "origin_departure_time"=>"2011-12-13 18:08:15 +0000", "destination_arrival_time"=>"2011-12-13 20:08:15 +0000", "destination_departure_time"=>"2011-12-13 23:08:15 +0000", "origin_arrival_time"=>"2011-12-13 22:08:15 +0000", "organiser_attributes"=>{"email"=>"email@example.com", "name"=>"Peter Pan", "phone"=>"1234543534"}}}
   (0.0ms)  SAVEPOINT active_record_1
   (0.1ms)  SELECT 1 FROM "guest_users" WHERE "guest_users"."email" = 'email@example.com' LIMIT 1
   (0.0ms)  ROLLBACK TO SAVEPOINT active_record_1
Completed 422 Unprocessable Entity in 6ms (Views: 0.3ms | ActiveRecord: 0.1ms)
   (0.0ms)  SELECT COUNT(*) FROM "trips"

这是怎么回事?顺便说一句,我正在使用Rails 3.1.3。

1 个答案:

答案 0 :(得分:1)

通常,您将accepts_nested_attributes_for放在作为关系父级的模型中(也就是拥有关联的类),即包含has_many:chidren语句的模型。