我无法弄清楚如何通过嵌套模型收集一些数据出现在“show”页面上。我有一个包含3个模型的rails应用程序,用户模型,项目模型和团队模型。模型关联如下:
项目: -
class Project < ActiveRecord::Base
has_many :users, :through => :team
has_one :team, :dependent => :destroy
accepts_nested_attributes_for :team, allow_destroy: true
end
小组: -
class Team < ActiveRecord::Base
belongs_to :project
has_many :users
end
用户: -
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_and_belongs_to_many :teams
end
每个项目都有一个团队,每个团队都包含许多已保存在数据库中的用户。我想要做的就是能够在Project表单中选择多个现有用户(通过嵌套表单)并将其保存到名为Team的模型中。我设法使表单正常工作,但我不知道如何将收集的数据保存到团队模型,然后使所选的用户组(团队)出现在项目的显示页面中,因为那里涉及3个模型。请帮忙!
P.S我使用嵌套表单gem在项目表单中添加多个团队成员。
项目显示页面: -
<%= bootstrap_nested_form_for(@project, :html => {:multipart => true}, layout: :horizontal) do |f| %>
<% f.fields_for :teams do |builder| %>
<% if builder.object.new_record? %>
<%= builder.collection_select :user, User.all, :id, :email, { prompt: "Please select", :selected => params[:user], label: "Employee" } %>
<% else %>
<%= builder.hidden_field :_destroy %>
<%= builder.link_to_remove "Remove" %>
<% end %>
<%= f.link_to_add "Add Team Member", :teams %>
<%= f.submit %>
<% end %>
项目控制器: -
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@projects = Project.all
respond_with(@projects)
end
def show
respond_with(@project)
end
def new
@project = Project.new
@project.pictures.build
@project.teams.build
respond_with(@project)
end
def edit
@project = Project.find(params[:id])
@project.pictures.build
@project.teams.build
end
def create
@project = Project.new(project_params)
if @project.save
flash[:notice] = "Successfully created project."
redirect_to @project
else
render :action => 'new'
end
end
def update
@project.update(project_params)
respond_with(@project)
end
def destroy
@project.destroy
respond_with(@project)
end
private
def set_project
@project = Project.find(params[:id])
end
def project_params
params.require(:project).permit(:id, :title, :description, :status, :phase, :location, :image, pictures_attributes: [:id, :image], teams_attributes: [:project_id, :user_id])
end
end