1

I'm new to Ruby on Rails and I'm trying to update a device attribute (lastChangedBy) that will set its value to the user's IP address whenever the submit button is clicked. I wanted to do something like:

 <%= form_for(@device) do |f| %>
 .
 .
 .
 <%= if click? ( f.submit "Commit Entries", class: "btn btn-primary" ) == true %>    
      <%= @device.lastChangedBy = request.remote_ip %>
 <% end %>

but I don't think that's possible. I'm looking into using "button_to" but after searching online I am extremely confused to how to use it. I tried doing something like:

 <%= button_to "Commit Entries", action: "setIp" %>

and then in DevicesController & in the helper.rb (because I wasn't sure where it would call the method) I made a simple method:

 def setIp
      Device.find(params[:id])
  @device.lastChangedBy = request.remote_ip
 end

but I am completely lost. Could someone please help me. It would be amazing if you were specific!

2 Answers 2

1

If you're already submitting a form, and want to set that parameter, do it in the controller:

class DevicesController < ApplicationController

  def update
    @device = Device.find(params[:id])
    @device.last_changed_by = request.remote_ip # Tada!
    if @device.update_attributes(params[:device])
      redirect_to @device
    else
      render 'edit'
    end
  end

end

Tweak according to your application, but that's the basic idea.

Sign up to request clarification or add additional context in comments.

Comments

0

Since you mentioned that you are unsure of how to utilize calling a function with button_to, and that you already have a method in your controller you can approach it as follows, by adding some fields to your view's button_to. With this approach you'll also be able to remove your form.

=button_to 'SetIp', {:controller => "your_controller", 
     :action => "setIp", :id => your_model.id}, {:method => :post }

And in your routes.rb

resources :your_controller do    
    post :setIp, :on => :collection    
end

And in your_controller.rb

def setIp
    device = Device.find(params[:id])
    device.lastChangedBy = request.remote_ip
    device.save!

    #Can redirect to anywhere or render any page
    redirect_to action: :index
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.