简体   繁体   English

将数据库中的值设置为False取决于其他值,否则为True / False

[英]Setting value in database as False dependent on a different value else True/False

I am trying to set a value of an attribute in my MySQL DB using a ternary operator that is dependent on another variable/value that is available in the same model. 我试图使用三元运算符设置MySQL数据库中属性的值,该运算符取决于同一模型中可用的另一个变量/值。

item.rb has a belongs_to relationship to auction.rb . item.rbbelongs_to关系auction.rb An instance of an auction can be online_only or not. 拍卖的实例可以是online_only也可以不是online_only I am trying to set an attribute on an item instance called manual_close that is dependent on wether or not the auction is online_only or not. 我试图在一个名为manual_close的项目实例上设置一个属性,该属性取决于拍卖是否为online_only

so I have the following: 所以我有以下内容:

Item.rb: item.rb的:

def as_json(**options)
  json = {
    "manual_close" => self.manual_close?
  }
end

def manual_close?
  !online_only? false : self.manual_close
end

def online_only?
  auction && auction.online_only?
end

Say that item.online_only? == false 说那个item.online_only? == false item.online_only? == false then item.manual_close should == false if item.online_only? == true item.online_only? == false那么item.manual_close应该== false如果item.online_only? == true item.online_only? == true then item.manual_close can either be true or false. item.online_only? == true那么item.manual_close可以为true或false。

Some rails c output: 一些rails c输出:

在此处输入图片说明

a = Auction, i = Item. a =拍卖,i =物品。 The json part is right but when I do item.manual_close it should be false instead of true. json部分是正确的,但是当我执行item.manual_close它应该为false而不是true。

Any help would be much appreciated. 任何帮助将非常感激。

I think the problem here is that you are not updating your model in your database. 我认为这里的问题是您没有更新数据库中的模型。

Defining a method called manual_close? 定义一个名为manual_close?的方法manual_close? will only override the method manual_close? 只会覆盖方法manual_close? (with the question mark) and will not affect the manual_close attribute in your database. (带有问号),并且不会影响数据库中的manual_close属性。

You will have to explicitly update manual_close in your database to get the results you are looking for. 您将必须在数据库中显式更新manual_close以获得所需的结果。

i.update(manual_close: i.manual_close?)

I would recommend calling this line from an after_save callback on your Auction model. 我建议您从Auction模型上的after_save回调中调用此行。 That way, every time the the auction model is updated, the item model will correctly reflect the state it needs to be. 这样,每次拍卖模型更新时,项目模型将正确反映其所需的状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM