Search code examples
ruby-on-railsrubyruby-on-rails-4booleannested-resources

Boolean Toggle in Nested Form


I have a Issues Controller and a nested Comments Controller. My Comments form is in my Issues Show View.

I'm trying to add a checkbox when commenting that would toggle the :closed => boolean attribute on my Issue.

<%= form_for @issue.comments.build, url: script_issue_comments_path(@script, @issue) do |f| %>

<!-- Form , etc-->

<%= form_for [@script, @issue] do |f| %>
  <%= f.check_box :closed %> Mark as Closed
<% end %>

<% end %>

That obviously didn't work. How can achieve this ?

Basically i will put the checkbox right next to the submit button of the Comment.. So if selected, the Issue attribute :closed will be set to True


Solution

  • The inner form you have there isn't a nested form (in rails terms), and as you've found won't behave in the way you're wanting because it's not really tied to the submission of the outer form.

    One approach you could do, which would keep the comments controller from having responsibility of editing issues at the same time (which would be messy in my opinion), would be to have something like a comment_closes_issue attribute on the comment. Then, when you save the comment, if comment_closes_issue is true, then update the parent issue... It's still blurring the lines between the two models a little, but if they're closely tied, then perhaps that's ok in your application.

    Edit - here's an example of how to handle that, assuming a Comment belongs to an Issue:

    class Comment < ActiveRecord::Base
      belongs_to :issue
    
      after_save :close_parent_issue, if: :comment_closes_issue
    
      private
    
      def close_parent_issue
        issue.update_attributes closed: true
      end
    end
    

    Then in your view, you can just have <%= f.checkbox :comment_closes_issue %>...