簡體   English   中英

即使我在 rails 中定義了方法,我也無法調用它

[英]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 %>

我試圖激活該方法,但收到錯誤消息說沒有這樣的方法。

這是我的 controller 代碼。

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

在鏈接上指定一個method ,不會做你期望它做的事情,因為這不是你指定要執行哪個controller方法的方式。 method請求類型 要從這樣的鏈接點擊 controller 方法,您需要創建一條到它的路由並將其用作您的路徑。

路線.rb

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

我們在這里將方法設置為:patch ,因為您正在更新信息。 如果需要,您也可以使用:post ,但:patch可能更接近這里的最佳實踐。

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

你的方法也應該是這樣的

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

在此處查看有關軌道路由的文檔以獲取更多信息: https://guides.rubyonrails.org/routing.html#resources-on-the-web

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM