Home > Back-end >  Save 1 form field for 2 variables
Save 1 form field for 2 variables

Time:09-29

Hi Rails Beginner here,

I followed a tutorial guide that helped auto generate a bunch of files to help with the CRUD process of entities in my models, for my entities (books), they have a title, number of total copies, and number of available copies. Since new books should always have the total number of copies available, I want to remove the redudancy of asking the user to input the number of available copies by making the form field that takes in total number of copies be saved into 2 variables (total and available). But I'm not sure how to do it.

CodePudding user response:

It's always best to attach a code example to your questions.

Here are two ways how I would do it:

  1. I would only have one field in the form and then in the controller I would manually assign the number of available copies to the field of total copies.
# controller.rb
def create
  @book = Book.new(book_params)
  @book.total_copies = params.require(:book)[:available_copies]
  if @book.save
  ...
end
  1. You could add the total field as a hidden field and have a little snippet of JS that automatically puts in the same number as in the availabilty input on change of that input field.

Beware that the code is just a guess, you need to adapt it and use the column names from your DB

  • Related