简体   繁体   中英

problem with using form / formtastic on 2 objects

I am really having problems getting this thing done. I have a model appointment and a model appointment_block . The appointment_blocks table saves a start and end time as datetime. I am using a method called split_time_block , which splits me the timerange in 15-minute packets and returns it in an array of strings. This works fine. I can select the different times in the select-button. The appointments table refers to the appointment_block_id. With my form I want to send the block_id to my new appointment table entry. I only get null entries in this column.

= semantic_form_for(@appointment) do |f|
  -f.inputs do

    -@appointment_blocks.each do |form|
      =f.input :date, ,:as => :select, :collection =>  form.split_time_block

    = f.input :category, :collection => Category.all, :as => :select
    = f.input :memo

  - f.buttons do
    = f.commit_button

My appointments_controller contains:

@appointment = Appointment.new  
@appointment_blocks = AppointmentBlock.all

Thx for advise!!

appointment and appointment_block are not tied together in any meaningful way in your form (as you've discovered).

Assuming that you have accepts_nested_attributes_for set in your model(s):

semantic_form_for(@appointment) do |f|
   f.inputs do

    f.semantic_fields_for :appointment_block do |ab_form|
      ab_form.input :date, ,:as => :select, :collection => split_time_block
    end

    f.input :category, :collection => Category.all, :as => :select
    f.input :memo

    f.buttons do
    f.commit_button
end

Your form should look something along those lines. Then when your view is rendered, examine the markup, and you should see the proper nesting built into the element ids and names. When this gets sent to your controller and you instantiate an Appointment model object in your create function, you should be able to see your nested objects:

@appointment = Appointment.new params[:appointment]
flash[:notice] = @appointment.appointment_block.inspect <-- you should be able to see that the objects are nested properly, and in the db the id's line up properly.

Formtastic documentation (look about halfway down for nested forms)

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