通过lik使用put方法从“直通”模型更新属性

问题描述 投票:0回答:1

我有一个has_many :through关联。

class Book < ApplicationRecord
    has_many :applicants
    has_many :users, through: :applicants
end

class User < ApplicationRecord
    has_many :applicants
    has_many :books, through: :applicants
end

class Applicant < ApplicationRecord
    belongs_to :user
    belongs_to :book
end

当我在Rails控制台中手动创建关联时,它工作正常。

现在,我需要一种解决方案,通过单击模板中具有put方法的链接来创建关联。点击后,页面不应重新加载。用户已被触发,并且有权访问模板中的图书ID

我如何最好地解决这个问题?

ruby-on-rails associations has-many-through ruby-on-rails-6
1个回答
0
投票

您可以创建ApplicantsController并通过create操作处理创建>

class ApplicantsController < ApplicationController
  def create
    book = Book.find(params[:id])
    current_user.books << book

 ...

在视图中

  = link_to 'Add Book', applicants_path(book), method: 'post', remote: true

create.js.erb

  $("unique class or id of book link").text('Book Added')

申请人模型

class Applicant < ApplicationRecord
  validates_uniqueness_of :user_id, scope: :book_id
end
© www.soinside.com 2019 - 2024. All rights reserved.