Ruby on rails Rails-创建或更新记录。。。。If语句vs find或create by
我有 工作正常,但每次都会创建记录。我想检查for循环中是否存在具有相应兴趣id的记录,如果存在,我想更新,否则创建就可以了 我环顾四周,发现了“find_或create_by”方法,但它对我来说并不实用。我有=>Ruby on rails Rails-创建或更新记录。。。。If语句vs find或create by,ruby-on-rails,Ruby On Rails,我有 工作正常,但每次都会创建记录。我想检查for循环中是否存在具有相应兴趣id的记录,如果存在,我想更新,否则创建就可以了 我环顾四周,发现了“find_或create_by”方法,但它对我来说并不实用。我有=> @user = User.find(1) @event = Event.find(1) for interest in @event.interests @user.choices.create(:interest => interest, :score => 1)
@user = User.find(1)
@event = Event.find(1)
for interest in @event.interests
@user.choices.create(:interest => interest, :score => 1)
end
并得到错误“未定义的方法‘按兴趣查找’
你能看出我做错了什么吗?还是坚持使用if/else语句更好
我不确定find_或create_by方法是否具有update属性功能 再一次,如果我没有误解您试图实现的目标,您应该按照兴趣、id和分数进行查找或创建:
@user.choices.find_or_create_by_interest(:interest => interest.id, :score => 1)
我得到了错误。。。未知键:分数、兴趣???你以前见过吗?通过兴趣、id和分数(兴趣、id、1)查找或创建。但要当心!如果你有一个id正确但分数错误的对象,它会尝试创建它,但会失败:你不能有两个id相同的对象。是的……这是一种方法,但它不会更新在何处找到的记录……它只是在找不到记录时添加……我开始认为if/else语句可能是最好的选择
find_or_create_by_interest_id(:interest => interest.id) { |u| u.score = 1 }