我有3個模型User
Book
和List
。他們每個人都有彼此的關係。幾乎我想要做的是將一本書添加到用戶列表中。我正在使用best_in_place gem來更新書show.html.erb中用戶列表中的書。當我嘗試更新狀態時,它會回到空白。我不完全確定它爲什麼不更新。也許有人可以檢查我的代碼,看看我是否失去了一些東西。使用has_many:通過關聯和使用best_in_place寶石添加書籍
class List < ActiveRecord::Base
belongs_to :user
belongs_to :book
validates :book, uniqueness: { scope: :user_id, message: "%{attribute} already added" }
end
class Book < ActiveRecord::Base
has_many :lists
end
class User < ActiveRecord::Base
has_many :lists
has_many :books, through: :lists
end
列表控制器
class ListsController < ApplicationController
respond_to :html, :json
def create
@book = Book.find params[:book_id]
@list = current_user.lists.new list_params
@list.save
end
def update
@book = Book.find params[:book_id]
@list = current_user.lists.find(params[:id])
@list.update (list_params)
respond_with @list
end
def destroy
@book = Book.find params[:book_id]
@list = current_user.lists.find(params[:id]).destroy
end
private
def list_params
params.require(:list).permit(:status, :rating).merge(book_id: @book.id)
end
end
書籍控制器
class ListsController < ApplicationController
def show
@book = Book.find params[:id]
@list = current_user.lists.new
end
end
書籍/ show.html.erb
<%= best_in_place [@book, @list], :status, type: :select,
collection: [["Watching" , "Watching"],
["Completed" , "Completed"],
["On-Hold" , "On-Hold"],
["Dropped" , "Dropped"],
["Plan to Read" , "Plan to REad"]],
class: 'small dropdown button' %>
您可能需要仔細閱讀文檔。您可能需要添加書本控制器:respond_with_bip – mrvncaragay