I'm trying to learn web development as I go (I just need need to get this one project done. I don't plan on touching the subject ever again.) and I've run into the problem of getting data from a rails web page to its corresponding controller. My end goal is to get data from javascript variables and pass that to ruby, but I've decided to take small steps so for now I'm trying to get a button_to to send some hard coded strings from the new.html.erb to the corresponding create method in the controller. I've probably tried a hundred combinations of view, controller and, routs code and I can't get any of them to work. Here is the current iteration of my code for the controller, view, and routes (I'm not sure if routes even matters).
ponies_controller.rb
def create(name, pro)
#@pony = Pony.new(params[:id])
@pony = Pony.new(name: name, profession: pro)
respond_to do |format|
if @pony.save
format.html { redirect_to @pony, notice: 'Pony was successfully created.' } |~
format.json { render :show, status: :created, location: @pony }
else
format.html { render :new }
format.json { render json: @pony.errors, status: :unprocessable_entity }
end
end
end
new.html.erb
<h1>New Pony</h1>
<%= render 'form', pony: @pony %>
<%= link_to 'Back', ponies_path %>
<%= button_to "create_pony", {action: create("s","ss")}, remote: true,from_class: "create_pony" %>
routes.rb (Not sure if this is important)
Rails.application.routes.draw do
resources :ponies
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
post 'ponies/:id/create' => 'pony#create', as: :create_pony
end
While this code doesn't work I think it shows how I think things should work. I feel like I should just be able to call the method and be done with things, but that is obviously wrong. What should I be doing to get button_to to post a new "pony"?
resourceroute should already cover what you're defining with thepostmethod, so that second thing should be removed. Also, use link helpers to route things properly:new_pony_pathis the intention here. Note that controller methods do not take arguments. Everything will come throughparams.