[英]Update a record in a table in rails
I have a table A(:name, :flag) and want to update the flag column of a record in the table if a certain condition evaluates to true. 我有一个表A(:name,:flag),如果某个条件求值为true,则想更新表中记录的标志列。
if A.find(300).flag == false
//Will this work -> A.find(300).flag = true
What should I write in that line? 我应该在那一行写什么?
if A.find(300).flag == false
//Will this work -> A.find(300).flag = true
change to 改成
A.find(300).update(flag: true) if A.find(300).flag == false
You can add method to a.rb 您可以将方法添加到a.rb
def self.update_if_false id
find(id).update(flasg: true) if A.find(id).flag == false
end
Then you can use it as A.update_if_false(300)
然后您可以将其用作
A.update_if_false(300)
This will decrease database call if flag is true: 如果flag为true,这将减少数据库调用:
Rails 4: Rails 4:
obj = A.find(300)
obj.update(flag: true) unless obj.flag
Rails 3.2: Rails 3.2:
obj = A.find(300)
obj.update_attributes(flag: true) unless obj.flag
Note: update
method made public and aliased with update_attributes in active record 4. 注意:将
update
方法公开,并在活动记录4中使用update_attributes作为别名。
yes..it will work...i tried in ruby2.0 console.. Assuming you have all the attributes present.... 是的..它将起作用...我在ruby2.0控制台中尝试过.. 假设您具有所有存在的属性....
2.0.0-p481 :026 > Image.find(30).title = true
Image Load (7.8ms) SELECT "images".* FROM "images" WHERE "images"."id" = $1 LIMIT 1 [["id", 30]]
=> true
you can go ahead and add your update statement ..if true else false. 您可以继续添加更新语句..如果为true,否则为false。
if A.find(300).flag == false
##do something
else
##do other thing
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.