[英]Rails Association Has_Many
我正在尝试从与客户关联的书籍中获取信息,但似乎中间关联无效
这是我的模特
Book
has_one :book_manager
has_one :customer, :through => :book_manager
Customer
has_many :book_managers
has_many :books, :through => :book_managers
Book_Manager
belongs_to :customer
belongs_to :book
领域有
Book Customer book_manager
id id id
description email customer_id
password book_id
first visible
last
在def编辑中获取信息时,以下操作成功
@book = Book.first
@book = Book.last
以下似乎失败
@customer = Customer.find(params[:id])
@book = @customer.books.first
@book = @customer.books.order("created_at DESC").first
我有什么想念的吗?
我还尝试通过为book_manager控制器和视图创建索引来进行验证,但没有任何显示,它似乎是空的。 我的创作方式如下
BookController
def create
@book = current_customer.books.build(params[:book])
if @book.save
flash[:success] = "Book Created"
redirect_to root_url
else
render 'customer/edit'
end
end
我已经更新了我的关系,但仍然无法正常工作
这个想法是跟随
客户更新其状态,其中包括许多小节
-Phone
-Book
-Interest
在书本下,我应该查看是否存在与客户相关的空书,如果有,则展示最后一本书。 如果不是,则客户看到空白并可以创建一个新的
图书经理只是在那里维护关系,还因为我想保留数据,并且想让用户确定是否向站点中的其他所有人显示此数据。
这是我的建议。 我在sqlite3(带有内存数据库)中进行此操作仅出于演示目的。
连接(在rails中,改用database.yml):
ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database => ':memory:'
设置类:
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中,使用迁移):
Book.connection.create_table(Book.table_name) do |t|
t.string :description
t.integer :book_manager_id
end
BookManager.connection.create_table(BookManager.table_name) do |t|
t.boolean :visible
t.integer :customer_id
end
Customer.connection.create_table(Customer.table_name) do |t|
t.string :email
t.string :password
t.string :first
t.string :last
end
建立记录
cust = Customer.new :email => 'user@example.com'
cust.book_managers.build :visible => true
cust.book_managers.first.books.build :description => 'the odyssey'
cust.save!
取回
cust = Customer.find 1
# test the has_many :through
cust.books
# test the Book#customer method
Book.first.customer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.