-1

I'm wrapping a Rails app into an api, and this is part of the API app:

   # Merge existing yaml with post params
def merge_config(yaml, params)
  if params['post'].has_key? 'yaml'
    params['post']['yaml'].each do |key, value|
      if value == 'true'
        yaml[key] = true
      elsif value == 'false'
        yaml[key] = false
      else
        yaml[key] = value
      end
    end
  end

  yaml
end

# Update exiting post.
def update_post(params)
  post_file   = params[:post][:name]
  post        = jekyll_post(post_file)
  yaml_config = merge_config(post.data, params)
  write_post_contents(params[:post][:content], yaml_config, post_file)

  post_file
end


post '/save-post' do

  if params[:method] == 'put'
    filename = create_new_post(params)        
    log_message = "Created #{filename}"
  else
    filename = update_post(params)
    log_message = "Changed #{filename}"
  end

  # Stage the file for commit
  repo.add File.join(jekyll_site.source, *%w[_posts], filename)

  data = repo.commit_index log_message
  push_to_origin(repo)

  if params[:ajax]
    {:status => 'OK'}.to_json
  else
    redirect @base_url + '/edit/' + filename
  end
end

Here is my Rails code in my other app to access the save-post method. I am posting a form to it:

 def sendPostData
    uri = URI('http://immense-escarpment-7957.herokuapp.com/admin/save-post')

    req = Net::HTTP::Post.new(uri.path)
    req.basic_auth username, password
    req.body = params


    res = Net::HTTP.new(uri.host, uri.port)
    res.start {|http|
       http.request(req)
    }
    @textToShow = res
end

The internal form post is getting a 200, and here's the form data going into the sendPostData method (accessed by Chrome Developer Tools):

post[title]:jfklsdjflajs
post[name]:2014-05-22-jfklsdjflajs.md
post[content]:mycontentsadfasdfasd
post[yaml][title]:jfklsdjflajs
post[yaml][layout]:post
post[yaml][published]:true
post[yaml][hi]:hmmmmmmm
ajax:true
commit:SAVE

And a view attached to the API app has similar form data and is working:

post[title]:jkhjklhk
post[content]:
post[name]:2014-05-22-jkhjklhk.md
post[yaml][title]:jkhjklhk
post[yaml][layout]:post
post[yaml][published]:true
post[yaml][hi]:hmmmmmmm
ajax:true

However, the save-post method is returning a 500, and I'm getting this error in my logs:

2014-05-25T23:21:06.827121+00:00 app[web.1]: NoMethodError - undefined method `[]' for nil:NilClass:
2014-05-25T23:21:06.827129+00:00 app[web.1]:    /app/lib/pagoda/app.rb:83:in      `update_post'

Line 83 is this line:

post_file = params[:post][:name]

Am I not passing through the params correctly if it thinks this is nil?

zishe
  • 10,665
  • 12
  • 64
  • 103

1 Answers1

0

it is telling you that your params[:post] is nil.

Just follow this cue to hunt down why params[:post] is nil.

Or you can guard it:

post_file = params[:post][:name] if params[:post].present?
Steven Yap
  • 188
  • 6