gpt4 book ai didi

ruby-on-rails - 有很多通过删除链接的Rails

转载 作者:太空宇宙 更新时间:2023-11-03 16:27:23 24 4
gpt4 key购买 nike

我有一个大问题!

我有三个模型,School、Secretaries 和 Schools_Secretary。School_secretary 制作了一个连接模型,并且工作正常..但是添加记录后,我无法删除它。 ;(有人可以帮助我吗?

我不想删除 depent destroy,因为 School 和 Secretary 从未删除,我只想删除表 schools_secretaries 上的连接模型记录

秘书.rb

      class Secretary < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :schools_secretaries
has_many :schools, :through => :schools_secretaries,:uniq => true

end

学校.rb

class School < ActiveRecord::Base

has_many :schools_secretaries
has_many :secretaries, :through => :schools_secretaries,:uniq => true

end

schools_secretary.rb

class SchoolsSecretary < ActiveRecord::Base
belongs_to :secretary
belongs_to :school
end

routes.rb 访问 localhost/schools/1/secretaries/1

resources :schools  do
resources :schools_secretaries
resources :secretaries
devise_for :secretaries, :controllers => {:registrations => "registrations"}

结束

show.html.erb .. Action new 工作正常,我可以在表中插入寄存器

    <%= form_for [@school,SchoolsSecretary.new], :method => :post,:remote => true do  %>
<%= hidden_field_tag :school_id, @school.id %>
<%= hidden_field_tag :secretary_id, @secretary.id %>
<%= submit_tag 'Adicionar' %>
<% end %>

schools_secretaries_controller.rb

  def create
@school = School.find(params[:school_id])
@secretary = Secretary.find(params[:secretary_id])

schools_secretary_params = { :school_id => @school.id, :secretary_id => @secretary.id }

@schools_secretary = SchoolsSecretary.new(schools_secretary_params)

respond_to do |format|
if @schools_secretary.save
format.html { redirect_to @schools_secretary, notice: 'Schools secretary was successfully created.' }
#format.json { render action: 'show', status: :created, location: @schools_secretary }
else
format.html { render action: 'new' }
format.json { render json: @schools_secretary.errors, status: :unprocessable_entity }
end
end
end

最佳答案

要删除连接表记录,假设您有@school 和@secretary。现在试试下面的代码。

@school.secretaries.delete(@secretary)

关于ruby-on-rails - 有很多通过删除链接的Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22190260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com