我有以下模型(具有关联):
Page has_and_belongs_to_many Dimension
我的应用程序中有一组已定义的维度:
{id:1, width: 20, height:30}
{id:2, width: 40, height:60}
{id:3, width: 100, height:150}
用户创建页面时,我希望允许他设置尺寸数组,例如:
Page.create({:page_name => 'test', :dimensions_attributes => [{:width => 20, :height => 30}, {:width => 40, height: 60}])
这种方法的问题在于,它将在数据库中创建新的维度记录,而我不希望这样。我希望create方法去尝试提供给定宽度和高度的尺寸。
我怎样才能做到这一点?
我认为您应该为此在模型中添加一个方法,如下所示:
def add_dimensions=(dimensions_attributes)
dims.each { |attrs| dimensions << Dimension.find_or_create_by!(attrs) }
end
然后,你就需要更换:dimensions_attributes
为:add_dimensions
在您的来电Page.create
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句