Search code examples
ruby-on-railspathlink-to

Understanding the url part of a link_to, contain column name and value


Please explain me the url part of this link_to.

url part

admin_user_path(user,{ user: { admin: !user.admin? } })

full link_to

<%= link_to "#{ user.admin? }", admin_user_path(user,
  { user: { admin: !user.admin? } }),
  method: :patch,
  class: "admin #{ user.admin ? 'btn-warning' : 'btn-info' } " 
%>

this is the html

<a class="admin btn-warning " data-method="patch" href="/admin/users/2?
user%5Badmin%5D=false" rel="nofollow">true</a>

admin_user_path generates admin/user/

admin_user_path(user) it generates admin/user/:id

admin_user_path(user, options) i Think, the option part contains value, that is accessible in the controller through the params? With this value, i can save it for the record with the id of :id.

Sry, im still new to rails, and i want to understand the options part. i know, it's the magic of rails, but maybe there is a bit more explanation :)


Solution

  • I checked at Rails Guide, 2.9 Creating Paths and URLs From Objects : "In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters."

    For example:

    <%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>
    

    link_to Api documentation

    In your case

    admin_user_path(user,{ user: { admin: !user.admin? } })
    

    the option part creates a Boolean value, that’s available like you said in the Controller through parameters. Also, in your case I would recommend to check in your Controller that the user is actually admin, who accesses that path (authorization check).