简体   繁体   English

Rails 协会问题

[英]Rails associations question

I have two Models:我有两个模型:

Users, and Articles

Every user is able to create an article but can only edit his own Articles?每个用户都可以创建文章但只能编辑自己的文章?

Can someone provide an example of that?有人可以提供一个例子吗? (Model, Controller and View Please?) (型号,Controller 请查看?)

Thanks谢谢

EDIT编辑

I do not want the whole code.我不想要整个代码。 I can get the most of the code using scaffolding.我可以使用脚手架获得大部分代码。 I need the modifications that I have to do to achieve that.我需要我必须做的修改来实现这一点。 My biggest concern is how to allow only the author of an article to edit it.我最关心的是如何只允许文章的作者编辑它。 That's what I am asking.这就是我要问的。

I can't write the full example code out but I can at least point you in the right direction.我无法写出完整的示例代码,但我至少可以为您指明正确的方向。

You're describing a one to many association between your two models.您正在描述两个模型之间的一对多关联。 This guide is the best I've seen in figuring out how to set up those associations in Rails.本指南是我所见过的关于如何在 Rails 中建立这些关联的最佳指南。

Once you've got that in place you can limit access based on ownership of the article quite easily.一旦你有了它,你就可以很容易地根据文章的所有权来限制访问。 For something this straight forward you probably wouldn't need a permissions gem but there are some solid ones out there.对于这种直截了当的事情,您可能不需要权限 gem,但那里有一些可靠的。

I'd protect access in the controllers and in the view.我会保护控制器和视图中的访问。 You can simply check the current_user against the article object on the view, and in the controller you can use before filters to protect the article.您可以简单地根据视图上的文章 object 检查 current_user,在 controller 中您可以使用前置过滤器来保护文章。

If you get further down this path and have more specific questions I'm glad to try and answer them.如果您在这条道路上走得更远并且有更具体的问题,我很乐意尝试回答这些问题。

Assuming an Article belongs_to:user and you have an authentication setup that gives you a current_user method, you should be able to do something like this in your ArticlesController:假设一个 Article belongs_to:user并且你有一个身份验证设置,它为你提供了一个current_user方法,你应该能够在你的 ArticlesController 中做这样的事情:

def edit
  @article = Article.find(params[:id])

  if @article.user == current_user
    render :edit
  else
    flash[:alert] = "You don't have permission to edit this article."
    redirect_to some_path
  end
end

You would also need something similar for your update method.您的update方法还需要类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM