3

我正在嘗試find_or_create關聯模型,該模型正在通過accepts_nested_attributes_for接受。試圖通過accept_nested_attributes_for find_or_create?

我有一個旅行模式

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 protected]", "name"=>"Peter Pan", "phone"=>"1234543534"}}} 
    (0.0ms) SAVEPOINT active_record_1 
    (0.1ms) SELECT 1 FROM "guest_users" WHERE "guest_users"."email" = '[email protected]' 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

通常情況下,您將accepts_nested_attributes_for放入作爲關係父級的模型(又名擁有關聯的類),即包含has_many:chidren語句的模型。

+0

我不停止它的工作?我的意思是,它可以並且從父母和小孩協會都有效。 –

+0

關鍵是'嵌套'這個詞:你通常會發現孩子嵌套在父母的巢穴中,而不是相反 – maprihoda