在Ruby on Rails中,如果你无法在关联对象中正确呈现编辑和删除按钮,这通常涉及到几个方面的问题,包括路由设置、权限控制、视图模板编写等。下面我将详细解释这些问题,并提供相应的解决方案。
在Rails中,编辑和删除按钮通常是通过链接(link_to
)来实现的,这些链接会指向相应的控制器动作。对于关联对象,你需要确保路由设置正确,并且你有权限执行这些动作。
link_to
方法或者没有传递正确的参数。确保你的路由文件(通常是config/routes.rb
)中有正确的嵌套资源路由。例如:
resources :posts do
resources :comments, only: [:edit, :update, :destroy]
end
这将创建如下的路由:
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
update_post_comment PATCH /posts/:post_id/comments/:id(.:format) comments#update
destroy_post_comment DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
使用Rails的授权库(如CanCanCan或Pundit)来管理权限。例如,使用CanCanCan:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can [:edit, :update, :destroy], Comment, post: { user_id: user.id }
end
end
在视图模板中,确保正确使用link_to
方法,并传递正确的参数。例如:
<% @post.comments.each do |comment| %>
<div>
<%= comment.body %>
<% if can? :edit, comment %>
<%= link_to 'Edit', edit_post_comment_path(@post, comment) %>
<% end %>
<% if can? :destroy, comment %>
<%= link_to 'Destroy', post_comment_path(@post, comment), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
</div>
<% end %>
假设你有一个Post
模型和一个Comment
模型,它们之间是一对多的关系。以下是如何在视图中正确呈现编辑和删除按钮的示例:
config/routes.rb
Rails.application.routes.draw do
resources :posts do
resources :comments, only: [:edit, :update, :destroy]
end
end
app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can [:edit, :update, :destroy], Comment, post: { user_id: user.id }
end
end
app/views/posts/show.html.erb
<h1><%= @post.title %></h1>
<% @post.comments.each do |comment| %>
<div>
<%= comment.body %>
<% if can? :edit, comment %>
<%= link_to 'Edit', edit_post_comment_path(@post, comment) %>
<% end %>
<% if can? :destroy, comment %>
<%= link_to 'Destroy', post_comment_path(@post, comment), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
</div>
<% end %>
通过以上步骤,你应该能够正确地在Rails关联中呈现编辑和删除按钮。如果仍然遇到问题,请检查控制器中的相应动作是否正确实现,并确保数据库中的外键关系设置正确。
领取专属 10元无门槛券
手把手带您无忧上云