简体   繁体   English

如何使列依赖于一个模型中的其他列

[英]How to make a column depend on other columns in one model

  • There is a model Pair which consists of 3 string fields: arr1 , arr2 , arr3 有一个模型Pair ,它由3个字符串字段组成: arr1arr2arr3
  • I input the values of arr1 and arr2 and 我输入arr1arr2和的值
  • I want arr3 value to consist of similar numbers from arr1 and arr2 我希望arr3值由arr1arr2的相似数字组成
    after the comparison of arr1 and arr2 在比较arr1arr2

I'm not sure where to place the code for comparison arr1 and arr2 , because 我不知道在哪里放置比较 arr1arr2 的代码 ,因为
it doens't work in the new method PairsController : 它在new方法PairsController

    @pair = Pair.find(params[:id])
    @A = @pair.arr1.split & @pair.arr2.split
    @arr3 = @A.join(" ")

the output of arr1 , arr2 , arr3 in a table: arr1arr2arr3在表中的输出

...
<td><%= pair.arr1 %></td>
<td><%= pair.arr2 %></td>
<td><%= pair.arr3%></td>
...

the input of arr1 and arr2 in a layout: arr1和arr2在布局中的输入

...
<p><%= f.text_field :arr1 %></p>
<p><%= f.text_field :arr2 %></p>
...

What the table looks like now: https://i.imgur.com/43olFAi.png 现在的表格如下: https//i.imgur.com/43olFAi.png

Where should I place the comparison code and how to send the value to arr3 ? 我应该在哪里放置比较代码以及如何将值发送到arr3

There are many-many ways to do it. 有很多方法可以做到这一点。

For example using some callback in your model. 例如,在模型中使用一些回调。

class Pair < ApplicationRecord
  before_save :set_up_arr3

  def set_up_arr3
    self.arr3 = (arr1.split & arr2.split).join(" ")
  end
end

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

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