Skip to content

Instantly share code, notes, and snippets.

@tienshunlo
Last active August 29, 2015 14:25
Show Gist options
  • Save tienshunlo/3b047979a2ac354e72be to your computer and use it in GitHub Desktop.
Save tienshunlo/3b047979a2ac354e72be to your computer and use it in GitHub Desktop.
Rails 4 nested attributes and has_many :through associaton in a form
<p>
<%= f.label :name %><br/>
<%= f.text_field :name %>
<div class="field">
<%= f.fields_for :questionnaire_surveys do |ff| %>
<%= ff.fields_for :survey do |builder| %>
<% @surveys.each do |survey| %>
<%= builder.check_box :id, {}, survey.id %>
<%= builder.label survey.name %>
<% end %>
<% end %>
<% end %>
</div>
</p>
---阿芝解答-----
<div class="field">
<% @surveys.each do |survey| %>
<%= check_box_tag "questionnaire[questionnaire_surveys_attributes][][survey_id]", survey.id %>
<%= label_tag survey.name %>
<% end %>
</div>
class Questionnaire < ActiveRecord::Base
has_many :questionnaire_surveys
has_many :surveys, through: :questionnaire_surveys
accepts_nested_attributes_for :questionnaire_surveys
end
def questionnaire_params
params.require(:questionnaire).permit(questionnaire_surveys_attributes: [survey_attributes:[]])
end
---阿芝解答-----
params.require(:questionnaire).permit(:name, questionnaire_surveys_attributes: [:survey_id])
class QuestionnaireSurvey < ActiveRecord::Base
belongs_to :questionnaire
belongs_to :survey
accepts_nested_attributes_for :survey
end
Class Survey
has_many :questionnaire_surveys
has_many :questionnaires, through: :questionnaire_surveys
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment