我有两个模型,Collection和Book。一本书属于一个集合,一个集合有很多书。
我以这种方式生成了我的模型:
bin/rails generate model Collection title:string plot:text
bin/rails generate model Book title:string plot:text Collection:references
然后它生成这些模型:
class Book < ActiveRecord::Base
belongs_to :Collection
end
class Collection < ActiveRecord::Base
end
所以我已经读过像这样的其他答案has_many, belongs_to relation in active record migration rails 4我必须在Collection模型中手动添加has_many字段。
好的,它看起来像这样:
class Collection < ActiveRecord::Base
has_many :books
end
然后我运行迁移:
bin/rake db:migrate
然后我添加一些数据,几本书和一个集合(我不确定收集帖是否正确):
curl -H 'Content-Type: application/json' -X POST -d '{"title" : "Book 1", "plot" : "book"}' http://127.0.0.1:3000/books
curl -H 'Content-Type: application/json' -X POST -d '{"title" : "Book 2", "plot" : "book"}' http://127.0.0.1:3000/books
curl -H 'Content-Type: application/json' -X POST -d '{"title" : "Collection", "plot" : "collection", "book_id" : [1,2]}' http://127.0.0.1:3000/collections
然后我在http://127.0.0.1:3000/collections检查它们并崩溃
def index
@collections = Collection.all
render :json => @collections.as_json(
:include => :book
)
end
它说
#p>未定义的方法`book'for#Did you 意思?书籍书籍
如果我尝试并用书替换书籍,那么书籍清单是空的:
[{"id":1,"title":"Collection","plot":"collection","created_at":"2016-04-11T17:53:38.892Z","updated_at":"2016-04-11T17:53:38.892Z","books":[]}]
这是我的创建方法:
def create
@collection = Collection.new(collection_params)
@collection.save
redirect_to @collection
end
private
def collection_params
params.permit(:title, :plot, :book_id)
end
它不应该把书存放在收藏中吗?为什么不出现在索引视图中?
答案 0 :(得分:2)
如果书籍属于馆藏,那么你希望collection_id能够存在于书籍表中,然后在创建数据时你想要这样做:
curl -H 'Content-Type: application/json' -X POST -d '{
"title" : "Collection",
"plot" : "collection"}'
http://127.0.0.1:3000/collections
curl -H 'Content-Type: application/json' -X POST -d '{
"title" : "Book 1",
"plot" : "book",
"collection_id": "1"}'
http://127.0.0.1:3000/books
curl -H 'Content-Type: application/json' -X POST -d '{
"title" : "Book 2",
"plot" : "book",
"collection_id": "1"}'
http://127.0.0.1:3000/books