Search code examples
ruby-on-railsruby-on-rails-4strong-parameters

Rails 4: Link tag that creates a record doesn't work with strong params


I'd like to create a new post simply by clicking a link. When I create this button, I get an error (below):

HTML:

<%= link_to 'Create That Post', {
    controller: 'posts',
    action: 'create',
    user_id: '123',
    title: 'Test Create a Post'
  },
  method: 'post',
  class: "btn btn-sm btn-success instagramBtn",
  id: "createPostBtn"
%>

Error:

param is missing or the value is empty: post

private
  def post_params
    params.require(:post).permit(  # Error points to this line.
      :title, 
      :description, 
      :user_id

This error seems reasonable, since the params being passed in are not in a post hash, like post[title]. Am I setting up the params wrong when I do my <%= link_to ... %>?


Solution

  • If you are not using the post params and the params can't change, don't use strong params. Just catch the content of the params you need and create the post.

    def new_post_from_button
      @post = Post.create(user_id: params[:user_id], title: params[:title])
    end
    

    As an alternative just remove the .require from the permits method.

    private
    
    def fixed_strong_params
      params.permit(:user_id, :title)
    end