0

这里我有 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 和书籍并具有适当的关联。另请注意,可见的布尔下拉菜单将在那里允许 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
4

0 回答 0