【发布时间】:2016-12-12 18:31:05
【问题描述】:
如果我有一个Book 实体和一个Chapter 实体,我的chapters_controller 的强参数应该是什么?
注意:我使用的是 JSON API。
在我的chapters_controller 中,我的强参数应该是:
:title, :order, :content, :published, :book, :picture
或者应该是:
:title, :order, :content, :published, :book_id, :picture
如果我使用:book 而不是:book_id,那么在我的Ember 应用程序中,当我去创建一个新章节时,我可以创建它并将该章节关联到父书,但是,我的测试失败了:
def setup
@book = books(:one)
@new_chapter = {
title: "Cooked Wolf Dinner",
order: 4,
published: false,
content: "The bad wolf was very mad. He was determined to eat the little pig so he climbed down the chimney.",
book: @book
}
end
def format_jsonapi(params)
params = {
data: {
type: "books",
attributes: params
}
}
return params
end
...
test "chapter create - should create new chapter assigned to an existing book" do
assert_difference "Chapter.count", +1 do
post chapters_path, params: format_jsonapi(@new_chapter), headers: user_authenticated_header(@jim)
assert_response :created
json = JSON.parse(response.body)
attributes = json['data']['attributes']
assert_equal "Cooked Wolf Dinner", attributes['title']
assert_equal 4, attributes['order']
assert_equal false, attributes['published']
assert_equal @book.title, attributes['book']['title']
end
end
我的控制台出现错误,提示关联类型不匹配。
也许我的台词:
book: @book
是什么原因造成的?
无论如何,直觉告诉我应该在我的chapters_controller 强参数中使用:book。
只是我的测试没有通过,我不确定如何编写参数哈希以使我的测试通过。
【问题讨论】:
标签: ruby-on-rails unit-testing ember.js strong-parameters json-api