Sean Stevens Sean Stevens - 2 months ago 8
Ruby Question

Using button_to to create new record in database, error: param is missing or the value is empty

I am trying to create a very basic button_to that will create a new record in the database. At the moment, I am hard coding in the 'video_id'. However, I am getting the following error:

param is missing or the value is empty: track

Request

Parameters:

{"authenticity_token"=>"e60ap2UFOpyfCLPrqRpvYCyZrfQwZ8DtmBglYu4n",
"video_id"=>"1"}


My create method in my 'Tracks' controller looks like this:

def create
Track.create(track_params)
redirect_to root_path
end

def track_params
params.require(:track).permit(:video_id)
end


My button_to in my application.html.erb looks like this

<%= button_to 'Save track', {:controller => "tracks", :action => "create", :video_id => "1" } , :method=>:post %>


Any help would be gratefully appreciated as I've been banging my head trying to solve this error for quite a while. To put things in context, what I ultimately want to achieve is the following solution: User searches for a keyphrase (a music video), which queries the Youtube API and displays the top 3 results. The user can then click the 'Save track' button to save the video_id of one of the three youtube videos to the track database. I've got up to the point where I can display the videos and now I'm trying to add this button.

Thanks in advance

Answer

Your problem in <%= button_to 'Save track', {:controller => "tracks", :action => "create", :video_id => "1" } , :method=>:post %>

this is not good way to build form (button_to generates a form containing a single button that submits to the URL created by the set of options.)

if you still want use button_to helper try pass simple path with params:

<%= button_to 'Save track', "/tracks/create?video_id=5"  , :method=>:post %>
                           ^^^^^^^^^|^^^^^^|^^^^^^^^^^
                          controller|action|params

this should generates html like this:

<form action="/tracks/create?video_id=5" class="button_to" method="post">
  <div>
    <input type="submit" value="Save track">
    <input name="authenticity_token" type="hidden" value="dUZL6a3NmlEZK9aVPEKX4rTxj/dTH2ZeBw1vCybWI8w=">
  </div>
</form>

Permit params:

def create
   Track.create(params.permit(:video_id))
   redirect_to root_path
end

Rails way for your case it is use _path helper and link_to helper.

Happy hacking.