How to pass a parameter in a link_to Rails

0

the question is the following, I have a Model called publications, in this model I have an integer attribute called: reason, what I want to do is that before the user accesses the view of the form to create publication there is a previous view with two links, for example in my case one that says "Rent (lease)" and the other "Sell", then the user when accessing one of these two links the attribute parameter: reason is automatically placed in 1 if it is selling or in 2 if it is to rent, thus entering the filling of the form but with this attribute already prescribed. What would be the format of those link_to? Do I have to add an equal route?

    
asked by Alvaro Andres Ponce Norambuena 12.05.2017 в 04:12
source

1 answer

1

From what I understand of your question ( How to pass a parameter in a link_to Rails ), what you need is not a variable motivo in your Model, but a local variable (in your < strong> initial view ) that you pass to the controller, through Hash params , and finally from the controller to the view of new post .

#index.html.erb
<%= link_to "Vender", new_publication_path(:motivo => "1") %>
<%= link_to "Alquilar", new_publication_path(:motivo => "2") %>

And once you have it in the Hash Params , you save it in an instance variable in the corresponding action (for what I understand it is in new you need it):

#/app/controllers/publications_controller.rb
def new
    @motivo_recibido = params[:motivo]
    ...
end

And taking it in an instance variable you can implement the logic you need to do. In the view new you can verify what content has the variable with debug :

#/app/views/publications/new.html.erb
<%= debug @motivo_recibido %>

Note : if you really need to save this variable in your Model, you can also do it by assigning this value, but to implement the sending of that data from an initial view em> until a view of new post is not needed.

    
answered by 12.05.2017 / 14:56
source