我有一个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
我如何最好地解决这个问题?
您可以创建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