I'm trying to do something very simple in my first Rails app (Rails 3) and I'm not sure what I'm doing wrong, or if there's a better approach. Can't find anything on the web or here that has solved it for me despite much searching.
In the app I have WorkRequests and Articles. When viewing an Article, I want a button to create a WorkRequest and, when the new WorkRequest form appears, have the article filled in. Essentially, I'm trying to pass the Article.id to the new WorkRequest.
Works in link_to just by adding the parameter, but I want it to be a button. While it shows up in the Article form's HTML as a query parameter, it never gets to the WorkRequest.new method. This article from 2010 explains the problem in some detail, but the solution does not work for me (see my comment at the end of the page.)
This seems like it should be a fairly easy and common thing to do (once I figure it out, there are several other places in my own app where I want to do the same thing) but I've been banging my head against this particular wall for a few days now. I am new to Rails--this is my first app--so I hope someone more experienced can help!
Thanks in advance.
Add this line of code in your routes.rb file.
It shouldn't be the GET method because you're sending information to the server, via :module_id. This will then work.
If you nest your
resources
for:work_requests
within:articles
in yourroutes.rb
, then pass yourparams[:id]
which would be yourarticle_id
and add:method => :get
to thebutton_to
call, you should be okay.In article#show
<%= button_to("Add WorkRequest", {:controller => "work_request", :action => "new", :article_id => @article.id})%>
In work_requests#new
<%= f.text_field :article_id, :value => params[:article_id]%>
Just circling back to finish this up. Ultimately I solved this by using link_to but using jQuery to make it look like a button. @kishie, if you're saying you made this work with button_to I'd like to see the code, but as I like jQuery it's solved as far as I'm concerned (for this app, anyway.)
Here's the code in Article#show view. (The class is what makes it look like a button via jQuery.)
Here's the code in Work_Request controller's new method:
Then the Work_Request#new view renders it properly.
I just hit a similar issue and I got it to work by passing the parameter as follows: