首页 > 解决方案 > Rails 嵌套表单 - 从 Club 创建新会议

问题描述

我有一个User,MeetingClub模型。

一个Userhas_many :user_clubs, has_many :clubs, :through => :user_clubs。

一个Clubhas_many :user_clubs、has_many :users、:through => :user_clubs 和 has_many :meetings

一个Meetingbelongs_to :club 和 has_many :users

我面临的麻烦是通过嵌套路由创建一个新会议: http://localhost:3000/clubs/1/meetings/new.

当我尝试创建会议时,我收到验证错误“俱乐部必须存在”。我知道这可以被覆盖,因为belongs_to 关联需要Club。但是,我不需要覆盖它——因为每次会议都应该属于一个俱乐部。我只是不知道如何正确解决错误。

我的路线是:

resources :users
resources :clubs do
  resources :meetings, only: [:show, :index, :new, :create, :edit, :update]
end

resources :meetings, only: [:index, :show, :new, :create, :edit, :update]

我的会议#new 操作如下所示:

def new
  @club = Club.find(params[:club_id])
  @meeting = Meeting.new
end

和会议#create:

def create
  binding.pry
  @meeting = Meeting.new(meeting_params)
  if @meeting.save
    binding.pry
    redirect_to club_path, notice: "Meeting was succesfully created."
  else
    render :new
  end
end

我的会议new模板正在使用form_for(@meeting) do |f|. 如何club将验证所需的内容传递给 Meetings#create?流程是:用户显示页面单击俱乐部> 俱乐部显示页面单击按钮以创建新会议> 会议#new 页面类型在名称、描述、时间和点击创建> 会议#index 页面我无法通过会议#new页。

标签: ruby-on-railsform-fornested-form-for

解决方案


解决了。答案在我的form_for. 我需要将其更改为:

<%= form_for [@club, @meeting] do |f| %> 

推荐阅读