Last active
August 29, 2015 14:25
-
-
Save tienshunlo/3b047979a2ac354e72be to your computer and use it in GitHub Desktop.
Rails 4 nested attributes and has_many :through associaton in a form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Questionnaire < ActiveRecord::Base | |
has_many :questionnaire_surveys | |
has_many :surveys, through: :questionnaire_surveys | |
accepts_nested_attributes_for :questionnaire_surveys | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def questionnaire_params | |
params.require(:questionnaire).permit(questionnaire_surveys_attributes: [survey_attributes:[]]) | |
end | |
---阿芝解答----- | |
params.require(:questionnaire).permit(:name, questionnaire_surveys_attributes: [:survey_id]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class QuestionnaireSurvey < ActiveRecord::Base | |
belongs_to :questionnaire | |
belongs_to :survey | |
accepts_nested_attributes_for :survey | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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