简体   繁体   中英

I cannot call method even though I defined it in rails

<% @links.each do |link|  %>

   <p class="source list-group-item"><%= link_to 'Plz', songs_path, 
method: :current_user.save_link(link), data: {confirm: "Are you sure?"} %></p>

<% end %>

I tried to activate the method but getting error saying there is no such a method.

Here is my controller code.

def self.save_link(linkurl)
        @current_user = current_user.artist_url 
        @current_user= linkurl
        @current_user.save
        flash[:notice] = "Saved!"
        redirect_to root_path
end

Specifying a method on a link, doesn't do what you're expecting it to do because that's not how you specify which controller method is going to be executed. The method is the request type . To hit a controller method from a link like this, you need to create a route to it and use it as your path.

routes.rb

patch '/save_link', to: 'controller#save_link'

We set the method to :patch here because you're updating information. You could also use :post if you wanted, but :patch is probably closer to best practice here.

<%= link_to 'Plz', save_link_path(link: link), method: :patch, data: {confirm: "Are you sure?"} %>

Your method should also look like this

def save_link
  @current_user = current_user.artist_url 
  @current_user = params[:link]
  @current_user.save
  flash[:notice] = "Saved!"
  redirect_to root_path
end

Check out the documentation on rails routing here for more information: https://guides.rubyonrails.org/routing.html#resources-on-the-web

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM