Wednesday, 15 April 2015

ruby - Rails 4 strong parameters for instance variable -



ruby - Rails 4 strong parameters for instance variable -

im using rails 4.1.6 , ruby 2.1.3

bookmarks_controller.rb

class bookmarkscontroller < applicationcontroller def index @bookmarks = listbookmarks.list render json: @bookmarks.to_json end def create @bookmark = createbookmark.new(params[:bookmark]).create if @bookmark head 201 else head 422 end end end

bookmarks_controller_test.rb

require 'test_helper' class bookmarkscontrollertest < actioncontroller::testcase test "return ok status if bookmark created" post :create, bookmark: { title: "tuts+", url: "http://tutsplus.com" } assert_response 201 end test "returns not ok status if bookmark not created" post :create, bookmark: {} assert_response 422 end end

create_bookmark.rb

class createbookmark def initialize info @data = info end def create bookmark = bookmark.new @data bookmark.save end end

but when run test returns:

activemodel::forbiddenattributeserror:

i have alter bookmarks_controller.rb this:

class bookmarkscontroller < applicationcontroller def index @bookmarks = listbookmarks.list render json: @bookmarks.to_json end def create @bookmark = createbookmark.new(bookmark_params).create if @bookmark head 201 else head 422 end end private def bookmark_params params.require(:bookmark).permit(:title, :url) end end

it returns next error:

actioncontroller::parametermissing: param missing or value empty: bookmark

i see updated initial post. , guess sec test case fails actioncontroller::parametermissing.

first of need clarify happens in code.

you sending request: post :create, bookmark: {}, params[:bookmark] empty sure. params.require(:bookmark) statement throws actioncontroller::parametermissing if params[:bookmark] empty or missing.

now lets think can depending on needs.

if want bookmark_params silently homecoming empty hash in case of missing params[:bookmark] can this: params.fetch(:bookmark, {}).permit(:title, :url)

in real world applications mutual pattern utilize params.require , rescue actioncontroller::parametermissing using rescue_from helper in applicationcontroller. maybe it's not in tutorial yet.

if want test action not create bookmark invalid input can seek send request invalid info e.g. post :create, bookmark: {asdasdasd: nil}.

ruby ruby-on-rails-4 rails-activerecord strong-parameters

No comments:

Post a Comment