2013-11-04 18 views
1

为什么使用collection_singular_ids = IDS VS update_attributes方法(:collection_ids)

@thing.tag_ids = params[:thing][:tag_ids] 

在数据库中保存一次的关系,但

@thing.update_attributes(params[:thing][:tag_ids]) 

不一样,如果验证失败?

@thing.update_attributes(params[:thing][:tag_ids]) 

相同

@thing.tag_ids = params[:thing][:tag_ids] 
@thing.save 

不是吗?

+2

'update_attribute'如何知道更新'tag_ids'?我认为你在那里有一些错误。 –

+0

'update_attributes'期望一个或多个键/值对。你只有价值输入,没有钥匙。 –

回答

1

您是还挺正确的,下面的两个语句完全相同的:

# save 
@thing.key = value 
@thing.save 

# update 
@thing.update_attributes({key: value}) 

与您的代码的问题是,你有语法问题,你想:

@thing.update_attributes({tag_ids: params[:thing][:tag_ids]}) 
0

继承人的解决方案似乎,第一种方法是使用update_attribute更新单个属性,因此验证永远不会执行。但是,我们知道验证的的update_attributes情况下始终执行

在这里阅读更多: - http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute

+0

是的,但上面的两个注释也是正确的,你必须故意或错误地将@ tag_id从@thing中删除。update_attributes({tag_ids:params [:thing] [:tag_ids]})。因为没有这个,你的程序肯定会有错误 – Akshat

0

我也有这样的行为挣扎......

代码:

@thing.tag_ids = params[:thing][:tag_ids] 

在DB ad hoc中进行更改,并且它不会调用验证,因此:

@thing.update_attributes(params[:thing][:tag_ids]) 

@thing.tag_ids = params[:thing][:tag_ids] 
@thing.save 

总之不同:

@thing.tag_ids = params[:thing][:tag_ids] # makes changes in DB w/o validations 
@thing.save # runs validations before making changes to DB 

我也询问是否使用时,有可能运行验证:

@instance.collection_singular_ids = other_singular_ids 

作为一个快速解决我加覆盖方法父模型('东西')像这样:

def tag_ids=(ids) 
    super 
rescue ActiveRecord::RecordInvalid => e 
    self.errors.add(:base, e.message) 
end 

和验证,以防止在标签重复加入模型,像这样:

validates :tag_id, :uniqueness => {:scope => :thing_id} 

有没有人有一个更好的解决?

相关问题