我遇到问题正确设置我的工厂的has_many / has_many通过或has_and_belongs_to_many与验证的关联。客户端模型/工厂已被省略,但确实存在。通过与验证相关联来设置has_many到has_many的最佳方法是什么,其中需要传入属性?
我尝试了一些让它无法成功运行的方法。目前的相关代码如下(略有改动)。尝试了其他方法:在client_team之后(:create)和之前(:create)创建user_clients,client_teams上的traits和定义关联的user_clients,使用build_list / create_list代替铲运算符。
ClientTeam模型:
using( IDbCommand dbCommand = dbConnection.CreateCommand() )
{
dbCommand.CommandText = Properties.Settings.Default.UpdateCommand;
Dictionary<string,object> values = new Dictionary<string,object>()
{
{"@param1",this.Property1},
{"@param2",this.Property2},
// ...
};
foreach( var item in values )
{
var p = dbCommand.CreateParameter();
p.ParameterName = item.Key;
p.Value = item.Value;
dbCommand.Parameters.Add(p);
}
}
用户模型:
belongs_to :client
has_many :client_team_rosters
has_many :users, through: :client_team_rosters
ClientTeamRoster模型:
belongs_to :client
has_many :client_team_rosters
has_many :client_teams, through: :client_team_rosters
validates_presence_of :client_teams
相关工厂:
belongs_to :user
belongs_to :client_team
规格文件:
factory :client_team do
client
team_name "stuff"
end
factory :client_team_roster do
client
user
end
factory :user do
...
factory :user_client do
client
before(:create) do |user_client|
client_team = user_client.client.client_teams.first
user_client.client_team_rosters << FactoryGirl.build(:client_team_roster, user: user_client, client_team: client_team)
end
end
end
当前错误:
before(:each) do
@client = create(:client)
@client_team = create(:client_team, client: @client)
end
it "should do something" do
user_client = create(:user_client, client: @client)
end
答案 0 :(得分:1)
呃,所以在发布之后,我决定进行一些小调整,结果正常工作。我没有删除问题,而是发布我的修复程序以帮助其他人(希望减少试用和错误)
在user_client工厂中,将回调更改为:
before(:create) do |user_client|
client_team = user_client.client.client_teams.first
user_client.client_teams << client_team
end
其中模仿了我们如何在代码库中设置模型。我可以发誓我早些时候就这样做了,但是这次尝试一下就完成了
编辑:我们还有一个继承自:user_client的工厂。在这些情况下,before(:create)似乎没有触发。但是,可以使用以下命令初始化这些继承的工厂:client_teams =&gt; [client_team]创建/构建时