在我的軌道項目中,我有三個型號:Rails的許多一對多:通過關聯嵌套形式
class Subject < ActiveRecord::Base
has_many :enrolments
has_many :users, through: :enrolments , :foreign_key => :user_id
accepts_nested_attributes_for :enrolments
class User < ActiveRecord::Base
has_many :enrolments
has_many :subjects, through: :enrolments , :foreign_key => :subject_id
accepts_nested_attributes_for :enrolments
class Enrolment < ActiveRecord::Base
belongs_to :user
belongs_to :subject
accepts_nested_attributes_for :user
subjects_controller.rb
class SubjectsController < ApplicationController
def new
@subject = Subject.new
@user = User.find(params[:id])
@subject.enrolments.build(:user_id => @user.id)
end
def create
@subject= Subject.create(subject_params)
respond_to do |format|
if @subject.save
format.html { redirect_to @subject, notice: 'Subject was successfully created.' }
format.json { render :show, status: :created, location: @subject }
else
format.html { render :new }
format.json { render json: @subject.errors, status: :unprocessable_entity }
end
end
def subject_params
params.require(:subject).permit(:name,
enrolments_attributes: [ :user_id, :subject_id, :_destroy, user_attributes: [ :id, :email, :_destroy]]
)
end
end
視圖(用於測試,將使用繭插入多個用戶):
<div class="container" style="padding-left: 0px;">
<div class="col-md-9">
<p id="notice"><%= notice %></p>
<%= form_for @subject, html: {class: "form-horizontal"} do |f| %>
<fieldset id="recipe-meta">
<ol>
<li class="control-group">
<%= f.label :name, "Subject name", class: "control-label" %>
<div class="controls"><%= f.text_field :name %></div>
</li>
</ol>
</fieldset>
<fieldset>
<%= f.fields_for :enrolments do |enrolment| %>
<%= enrolment.hidden_field :subject_id %>
<%= enrolment.fields_for :user , User.new do |enrolment_user| %>
<%= enrolment_user.label :email %>
<%= enrolment_user.text_field :email %>
<% end %>
<% end %>
</fieldset>
<%= f.submit %>
<% end %>
</div>
</div>
意圖:在創建主題的同時手動註冊stu用戶帳戶凹入多個字段(電子郵件),然後插入多個user_id到登記表中。
例報名表:
id user_id subject_id
--------------------------------------
1 2 1
2 3 1
3 4 1
更新(代碼現在工作):
添加
@subject.enrolment.build
到SubjectControllerdef new
方法
用戶是在裏面的註冊,不是主題? – alkuzad