如何从has_many的两侧创建记录:通过关联?

时间:2019-01-21 11:34:37

标签: ruby-on-rails

如何从has_many的两侧添加一条记录,通过关联?

我已经成功地通过“健身房”页面中的表格成功地添加了一个人并将其从健身房中删除。

但是我不知道如何通过“人员”页面中的表格向人员添加和删除健身房。

我的模特:

class Person < ApplicationRecord
    has_one :membership
    has_one :gym, through: :membership
end

class Membership < ApplicationRecord
  belongs_to :person
  belongs_to :gym
end

class Gym < ApplicationRecord
    has_many :memberships
    has_many :people, through: :memberships
end

我的路线.rb:

Rails.application.routes.draw do

  resources :people

  resources :gyms do
    resources :memberships
  end

end

我的memberships_controller.rb:

class MembershipsController < ApplicationController

    def new
      @gym = Gym.find(params[:gym_id])
      @membership = @gym.memberships.new
    end

    def create
      @gym = Gym.find(params[:gym_id])
      @membership = @gym.memberships.new(membership_params)

      if @membership.save
        redirect_to gym_path(@gym)
      else
        render :new
      end
    end

    def destroy
      @gym = Gym.find(params[:gym_id])
      membership = @gym.memberships.find_by(person_id: (params[:id]))
      membership.destroy

      redirect_to @gym
    end

private

    def membership_params
        params.require(:membership).permit(:person_id)
    end

end

在“体育馆”页面中,我有一个链接,打开此表单以选择一个人并将其添加到体育馆(实际上在加入{中创建了person_idgym_id的新记录{1}}表)。

我的membership

memberships/_form.html.erb

在我的路线文件中,如果将成员资格资源嵌套在人员资源下并遵循相同的步骤,最终我将点击健身房资源已在使用的<%= form_with(model: [@gym, membership], local: true) do |form| %> <div class = "form-group"> <%= form.label :Person, class: "form-text" %> <%= form.collection_select(:person_id, Person.all, :id, :firstname, {include_blank: true}, class: "form-control") %> </div> <div class="actions"> <%= form.submit 'Submit Membership', class: "btn btn-primary" %> </div> <% end %> 操作。

我被困住了,想不通办法。

0 个答案:

没有答案