It is a memorandum.
Use the create action and include? Method on the child controller to search the data in the parent table, and if the same content as the searched data is included, save it in the column of the child table.
Use the include? Method to see if it contains data such as a number or string.
For example
Sample code
array = [aiueo, yayuyo]
puts array.include?(aiueo)
puts array.include?(yayuyo)
puts array.include?(wawon)
Execution result
true
true
false
And will be.
① Parents: parents table
id | word |
---|---|
1 | AIUEO |
Child: kids table (no data yet registered)
id | text | word_id |
---|---|---|
② It is assumed that word_id is included in @ kid's params through [Parent's view]-> [Child's view]-> [new action (data registration screen)].
This time we will search the contents of the "word" column of the parent table to see if it matches the data entered by the user. If they match, save. When saving the data, I want to determine whether the column information of the parent table is included, so add an arbitrary method name to the if statement. This time, let's say having_word ?.
I will write a method that actually processes.
① Define having_word ?.
kids_controller.rb
def having_word?
end
(2) Check whether specific data is included in the data (@kid) entered by the user (include?).
kids_controller.rb
def having_word?
@kid.include?
end
③ Provide a column for writing "how to check specific data". → Write () immediately after include ?.
kids_controller.rb
def having_word?
@kid.include?()
end
④ Describe @kid to refer to the params up to the create action.
kids_controller.rb
def having_word?
@kid.include?(@kid)
end
⑤ Get parent (parents table) information included in params
kids_controller.rb
def having_word?
@kid.include?(@kid.parent)
end
⑥ Extract the word column from the parent information acquired in "⑤".
kids_controller.rb
def having_word?
@kid.include?(@kid.parent.word)
end
In the parentheses of include ?, I think it's like going back from the child to the parent's information.
Parents: parents table
id | word |
---|---|
1 | AIUEO |
2 | energy |
3 | Run |
4 | english |
Child: kids table
id | text | word_id |
---|---|---|
1 | AIUEO | 1 |
2 | Aiueo order | 1 |
3 | Aiueo table | 1 |
4 | Aiueo composition | 1 |
5 | How are you? | 2 |
6 | I'm really fine. | 2 |
7 | Self-propelled power | 3 |
8 | Mileage | 3 |
9 | I have studied english for 5 years. | 4 |
10 | just a random english comment passing by. | 4 |
Since I am a beginner in programming, please point out any points that cannot be reached. I thought that it is necessary to understand and specify the problem that the validation error message is not displayed in the future.
Recommended Posts