简体   繁体   中英

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
  • I input the values of arr1 and arr2 and
  • I want arr3 value to consist of similar numbers from arr1 and arr2
    after the comparison of arr1 and arr2

I'm not sure where to place the code for comparison arr1 and arr2 , because
it doens't work in the new method 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:

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

the input of arr1 and arr2 in a layout:

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

What the table looks like now: https://i.imgur.com/43olFAi.png

Where should I place the comparison code and how to send the value to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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