ここに私は3つのモデルを持っています
Customer Book Book_Manager
id id id
first description customer_id
last book_managers visible
email
password
協会は次のとおりです
class Customer < ActiveRecord::Base
has_many :book_managers
has_many :books, :through => :book_managers
end
class BookManager < ActiveRecord::Base
belongs_to :customer
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :book_manager
def customer
book_manager.customer
end
end
これで、次のようにして、新しい顧客を作成し、Rails コンソールで新しい本を作成できます。
cust.book_managers.build :visible => true
cust.book_managers.first.books.build :description => 'the odyssey'
cust.save!
で、こう見ると
cust = Customer.find 1
cust.books
Book.first.customer
上記のコードは Rails コンソールで動作しました。しかし、コントローラーで機能させる必要があります。プロフィール ページのようなもので、顧客は customer#edit に入り、モデルの本を参照します。その時点で、初めての場合は何もない可能性があります。または、以前に何かがあった場合は、最後の本がテキスト フィールドの説明に表示されます。以前に以下のコードを試しましたが、book_manager は更新されませんでした
@book = @customer.books.order("created_at DESC").first
テキストフィールドが変更または作成されると、新しい book_manager と books が作成され、適切な関連付けが行われます。また、表示されている場合は true または false を許可し、book_manager モデルで変更できるように、表示されるブール値のドロップダウン メニューがあることに注意してください。
文法について申し訳ありません私はフランス語です.
私はフォローしていましたが、うまく機能していないようです
class BooksController < ApplicationController
def create
@book = current_customer.book_managers.build()
@book = @customer.book_managers.first.books.build(params[:book])
if @book.save
flash[:success] = "Book Created"
redirect_to root_url
else
render 'customer/edit'
end
end
end