Ruby on rails 如何获取FactoryGirl模型属性与has_和_-belish_有多个关联?
我正试图通过HABTM协会获取(:trip)的Ruby on rails 如何获取FactoryGirl模型属性与has_和_-belish_有多个关联?,ruby-on-rails,ruby,rspec,factory-bot,Ruby On Rails,Ruby,Rspec,Factory Bot,我正试图通过HABTM协会获取(:trip)的FactoryGirl.attributes\u:countries,因为控制器测试失败-:countries在:trip属性中缺席): TripsController: class TripsController < ApplicationController def create trip = Trip.new(create_params) if trip.save redirect_to trips_pat
FactoryGirl.attributes\u:countries
,因为控制器测试失败-:countries
在:trip
属性中缺席):
TripsController:
class TripsController < ApplicationController
def create
trip = Trip.new(create_params)
if trip.save
redirect_to trips_path, notice: 'Trip successfully created.'
else
redirect_to :back, alert: trip.errors.full_messages.join('<br>').html_safe
end
end
def create_params
params.require(:trip).permit(:end_date, :description, country_ids: [], countries: [])
end
end
出行模式:
class Trip < ActiveRecord::Base
# Associations
has_and_belongs_to_many :countries
#Validations
validate :require_at_least_one_country
private
def require_at_least_one_country
if country_ids.empty? && countries.count == 0
errors.add(:base, 'Please select at least one country')
end
end
end
尝试了以下操作:,但没有用。检查您的请求中是否确实发送了任何
国家/地区ID
请使用(:trip)的
attributes\u值更新您的帖子,以下是答案和解释:
FactoryGirl.define do
factory :trip do
description { Faker::Lorem.sentence }
end_date { DateTime.now + 1.day }
after(:build) do |trip, evaluator|
trip.countries << FactoryGirl.create(:country, :with_currencies)
end
end
end
FactoryGirl.attributes\u for(:trip)
返回
{
:description=>"Eum alias tenetur odit voluptatibus inventore qui nobis.",
:end_date=>Wed, 16 Sep 2015 11:48:28 +0300
}
{
:description=>"Assumenda sapiente pariatur facilis et architecto in.",
:end_date=>Wed, 16 Sep 2015 11:45:22 +0300,
:country_ids=>[4]
}
我曾经尝试使用has_和_besive_to _manyfor many to many,但曾经遇到过各种问题。我发现使用它会使设置更容易。本教程可能会有帮助:嗨,Alexey,问题不在Controller中,而是在FactoryGirl.attributes\u中。实际上,我的意思是,在这行代码中,{post:create,trip:attributes\u for(:trip)}
之前,没有发送国家ID,但我还不够确定。很高兴你自己解决了。
FactoryGirl.define do
factory :trip do
description { Faker::Lorem.sentence }
end_date { DateTime.now + 1.day }
after(:build) do |trip, evaluator|
trip.countries << FactoryGirl.create(:country, :with_currencies)
end
end
end
{
:description=>"Eum alias tenetur odit voluptatibus inventore qui nobis.",
:end_date=>Wed, 16 Sep 2015 11:48:28 +0300
}
FactoryGirl.define do
factory :trip do
description { Faker::Lorem.sentence }
end_date { DateTime.now + 1.day }
country_ids { [FactoryGirl.create(:country, :with_currencies).id] }
end
end
{
:description=>"Assumenda sapiente pariatur facilis et architecto in.",
:end_date=>Wed, 16 Sep 2015 11:45:22 +0300,
:country_ids=>[4]
}