2016-06-16 6 views
0

私にはUserBookListという3つのモデルがあります。彼らはお互いに関係を持っています。かなり私がそれをやろうとしているのは、ユーザーのリストに本を追加することです。私はbest_in_place宝石を使ってbook.html.erbの書籍のユーザーリストから本を更新しています。ステータスを更新しようとすると、空白に戻ります。なぜ私はそれが更新されていないのか分からない。たぶん、誰かが私のコードをチェックアウトして、何かが欠けているかどうかを調べることができます。has_many:throughアソシエーションと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' %> 
+0

ブックコントローラに追加する必要があるかもしれません:respond_with_bip – mrvncaragay

答えて

1

いくつかの構文エラーがあります。 - いいえ、かっこの後には、 fあなたのブックコントローラは "ListsController"と呼ばれています

さらに、私はBookをListに属しています。それはより論理的に聞こえる。 また、書籍がリストを通じて本のみを所有している場合、ブックはユーザーに属しません。

もう1つの書籍コントローラです。なぜあなたは本を見たときに新しいリストを作成するのですか?

ベスト・イン・プレース・ジェムにはコメントができません。しかし、いくつかのものを修正した後に、それを動作させることができるかもしれません。

+0

私が間違っている場合は私を修正してください。ある書籍はリストに属し、リストには多くの書籍がありますか? – Wesly

+0

これは正しいです。あなたのモデルリストは、 "belongs_to"リストを持たない "have_many books"でなければなりません。しかしそれはちょうどあなたのやり方をするかもしれません。これはちょうどこのように論理的です。 – Maxence

関連する問題