【问题标题】:Rails 4: How do I properly link_to edit_path on index?Rails 4:如何正确链接到索引上的编辑路径?
【发布时间】:2016-09-04 10:39:31
【问题描述】:

我是 Rails 新手,遇到了一个可能很容易回答的问题。我有一个控制器和模型(工具/工具),我从工具的显示页面链接了 edit_path。但是我怎样才能从我的索引和搜索页面链接它呢?

以下是相关代码: /app/controllers/tools_controller.rb

class ToolsController < ApplicationController
    before_action :find_tool, only: [:show, :edit, :update, :destroy]

    def index
        @tools = Tool.where(user_id: current_user).order("created_at DESC")
        @user = current_user
    end

    def search
        @tools = Tool.all
    end

    def show
    end

    def new
        @tool = current_user.tools.build
    end

    def create
        @tool = current_user.tools.build(tool_params)

        if @tool.save
            redirect_to tools_path
        else
            render 'new'
        end
    end

    def edit
    end

    def update
        if @tool.update(tool_params)
            redirect_to tools_path
        else
            render 'edit'
        end
    end

    def destroy
        @tool.destroy
        redirect_to tools_path
    end

    private

    def find_tool
        @tool = Tool.find(params[:id])
    end

    def tool_params
        params.require(:tool).permit(:title, :subtitle, :url)
    end
end

/app/views/tools/show.html.haml

%h1= @tool.title

= link_to "Back", :back
= link_to @tool.user.try(:username), '/users/'+@tool.user_id.to_s

= link_to "Edit", edit_tool_path(@tool)
= link_to "Delete", tool_path(@tool), method: :delete, data: { confirm: "Are you sure?" }
enter code here

/app/views/tools/index.html.haml

%h2 My Tools
- @tools.each do |tool|
    %h2= link_to tool.title, tool
    %p= tool.subtitle
    %p= link_to "Edit", edit_path
    %p= time_ago_in_words(tool.created_at)



-if @user.use_gravatar?
    = image_tag gravatar_for @user
- else
    = image_tag @user.avatar_filename.url

%h1= @user.username

= link_to "Edit", edit_user_registration_path

/app/views/tools/search.html.haml

- @tools.each do |tool|
    %h2= link_to tool.title, tool
    %p= tool.subtitle
    %p= link_to tool.user.try(:username), '/users/'+tool.user_id.to_s
    %p= link_to "Edit", edit_path
    %p= time_ago_in_words(tool.created_at)

我希望提供的数据足够,如果没有请告诉我。感谢您的所有回复。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 link-to


    【解决方案1】:

    由于您使用tool 变量循环通过@tools,您可以执行类似的操作。

    = link_to 'Edit', edit_tool_path(tool)
    

    这类似于您使用索引视图将tooltitle 链接到show 操作

    = link_to tool.title, tool

    您的索引视图应该类似于

    - @tools.each do |tool|
      %h2= link_to tool.title, tool
      %p= tool.subtitle
      %p= link_to "Edit", edit_tool_path(tool)
      %p= time_ago_in_words(tool.created_at)
    

    search 视图执行相同操作。

    希望这会有所帮助!

    【讨论】:

    • @J.Hübotter 很高兴它有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2022-10-16
    • 2014-07-04
    • 2020-03-19
    • 2016-04-16
    相关资源
    最近更新 更多