InesM
InesM

Reputation: 343

Reject creation of nested attribute if checkbox checked

I have a form in my rails app that accepts nested attributes. However, what I want to do is for rails to reject the creation of the nested model if a checkbox (outside the model itself) is checked.

Any idea on how to pass an attribute to the :reject_if option of the accepts_nested_attributes_for in the model from the controller?

Thank you very much in advance.

EDIT:

My controller looks like this:

def new
  @course = Course.new
  @course.course_template = CourseTemplate.new
end

def create
  @course = Course.new(course_params)
  @course.user = current_user
  if @course.save
    flash[:success] = t(".new_course_created_succefully")
    redirect_to courses_path
  else
    render 'new'
  end
end

And the form:

<%= form_for @course do |f| %>
  <%= render 'shared/error_messages', error_model: @course %>

  <div class="form-group has-feedback mb">
    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>
  </div>

  <div class="form-group has-feedback mb">
    <div class="checkbox c-checkbox needsclick">
      <label class="needsclick">
        <%= check_box_tag "template", "1", false, {class: "needsclick"} %>
        <span class="fa fa-check"></span>Is Template?
      </label>
    </div>
  </div>

  <%= f.fields_for :course_template do |ff| %>
    <div class="form-group has-feedback mb">
      <%= ff.label :name %>
      <%= ff.text_field :name %>
    </div>
  <% end %>
<% end %>

Upvotes: 0

Views: 307

Answers (1)

PhilVarg
PhilVarg

Reputation: 4820

send that checkbox as a parameter from the form and put the build operation inside an if statement. No need to bother with the reject_if You need to handle your create and build operations separately. so instead of passing your model all attributes, youll pass the model the model attributes, and the association, the nested attributes

# controller
course = Course.new(course_params.reject{|attrib| attrib == :course_template_attributes})

unless params[:skip_create]
  course.course_templates.build(course_params[:course_template_attributes]
end
...

what you need to do is conditionally create the course_templates, so you can just pass Course.new all your course_params because that creates both the course and the templates, which needs to be done separately.

Note I'm shorthanding with that reject statement up there. you can either manually add in the various params or better yet create another method with strong params and whitelist only the model attributes (not including the course_template_attributes)

additionally. the params[:skip_create] is whatever the parameter is for that checkbox that decides whether or not you want to create the templates

Upvotes: 1

Related Questions