ardavis
ardavis

Reputation: 9895

Rails 3.2 Two Forms, One Hidden

I have two sections in a form, and I have a button that toggles their visibility. Is there a way to restrict the submit button from sending parameters from the hidden one? It's unfortunately creating courses without names or numbers, and it is not selecting an existing course if I use the collection_select.

projects/new.html.haml

= form_for [@user, @project] do |f|

  # This part of the form is mostly shown to the user, but is failing to work correctly
  = f.collection_select :course_id, @courses, :id, :name, { prompt: true }

  # This part of the form is typically hidden, javascript reveals it.
  .hidden
    = f.fields_for :course do |builder|
      = builder.text_field :name, class: 'large', placeholder: 'Ex: Calculus I'
      = builder.label :number, 'Number'
      = builder.text_field :number, class: 'new_project_course_number', placeholder: 'Ex: MATH-101'
      = builder.hidden_field :user_id, value: current_user.id

project.rb

belongs_to :user
belongs_to :course

attr_accessible :course_id, :course_attributes
accepts_nested_attributes_for :course

course.rb

belongs_to :user
has_many :projects

user.rb

has_many :projects
has_many :courses

Please let me know if I am leaving off any vital information accidentally.

Upvotes: 0

Views: 249

Answers (1)

Johny
Johny

Reputation: 1441

I think you might be looking for reject_if param for your nested attribute set. For example:

accepts_nested_attributes_for : course, :reject_if => proc { |attributes| 
  attributes['name'].blank? 
}

Or something like this. It allows you leave submitted form as is it, but only created nested course object, when name is preset (in your case, there is some placeholder, so you might use another check here)

Upvotes: 1

Related Questions