I am new to rails and stuck with a probably easy to answer question. I have a controller and model (Tools / Tool) and I linked the edit_path from the show page of the Tool. But how can I also link it from my index and search page?
Here is the relevant code: /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)
I hope the provided data is enough, if not please tell me. I'm grateful for all Your replies.
Since you're looping through the @tools
using the tool
variable, you can do something like this.
= link_to 'Edit', edit_tool_path(tool)
This is similar to how you linked the tool
's title
to the show
action from index view using
= link_to tool.title, tool
Your index view should look something like
- @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)
Do the same for the search
view.
Hope this helps!