Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.