Passing parameters from view to controller
Solution 1
You can add information to the params hash right through the link_to. I'm not sure exactly what you are trying to do but I did something like this recently to add the type of email I wanted when I link to the new email
<%= link_to 'Send Thanks', new_invoice_email_path(@invoice, :type => "thanks") %>
Now my params looks like:
{"type"=>"thanks", "action"=>"new", "controller"=>"emails", "invoice_id"=>"17"}
I can access the type via the params
email_type = params[:type]
Instead of a string, if you pass in the instance variable @rela you will get the object_id in the params hash.
Per the comment below, I'm adding my routes to show why the path new_invoice_email_path works:
resources :invoices do
resources :emails
end
Solution 2
When a request comes in, the controller (and any model calls) will be processed first and then the view code gets processed last. The view can call methods in the helpers, but can't reference functions back in the controller.
However, once a page is rendered, you can either post information back to the controller as part of a new request or use ajax/JQuery (etc) to make a call to a controller function remotely.
Does that help?
OXp1845
Updated on July 09, 2022Comments
-
OXp1845 almost 2 years
I got a bit of a newbie question. I'm trying to pass a variable from my view to my controller. Is there anyway my method in my controller can receive variables from my view?
Post view: show.html.erb: .... <%=link_to "Add relationship", :method => :add_relationship(@rela) %>
Controller: post.controller.rb: def add_relationship(rela) @post = Post.find(params[:id]) if current_user.id == @post.user_id @post.rel_current_id = rela.id @post.save redirect_to relationships_url else redirect_to posts_url, :notice => "FY!" end end
Thanks in advance :)
-
OXp1845 over 11 yearsSorry, ajax is a little bit to complex for me :)
-
OXp1845 over 11 yearsYes, this is something that I am looking for. Is the new_invoice_email_path your controller or method? Pfft, I really need to learn more about this. I am more used to JAVA than ruby...
-
Steve over 11 yearsthis route takes me to the email controller, new action. Email is a nested route for invoice, I'll add my routes to my answer above
-
Chris Lewis over 11 yearsopen a command prompt and type 'rake routes' to see what defined routes you have. It also tells you what controller and action it maps to.