[英]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.rb
有belongs_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: 所以我有以下内容:
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。
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.