Rails 4:如何在索引上正确link_to edit_path?

时间:2016-09-04 10:39:32

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

我是新手,并且坚持一个可能很容易回答的问题。我有一个控制器和模型(工具/工具),我链接了工具的显示页面中的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)

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

1 个答案:

答案 0 :(得分:0)

由于您使用@tools变量循环遍历tool,因此您可以执行以下操作。

= link_to 'Edit', edit_tool_path(tool)

这类似于您使用

从索引视图将tool&#39; titleshow操作相关联的方式

= 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视图执行相同的操作。

希望这有帮助!