1

在我的应用程序中,我note.rb使用了如下所示的架构。我想要做的是限制编辑笔记的能力。基本上,如果笔记是在过去 24 小时内创建的,则允许您更新任何您想要的内容。24小时后,你所能做的就是改变remind_at时间。我在note.rb文件中有一个方法可以检查注释是否可编辑。如果是我显示不同的部分。但这仅限制了前端,如果有人打开编辑窗口或输入 URL,他们仍然可以在 24 小时后编辑注释。

我正在尝试做的是编写一个before_update方法来检查您是否被允许更新body笔记。不管什么你都可以更新remind_at时间。部分问题在于控制器知道这是否只是对remind_at时间的更改的方式是通过params[:reschedule]并且params在模型中无法访问。

# == Schema Information
#
# Table name: notes
#
#  id                :integer          not null, primary key
#  body              :text
#  remind_at         :datetime
#  created_at        :datetime
#  updated_at        :datetime

# Only allow editing of notes that are less that 1 day old
  def editable?
    self.created_at > (Time.now-1.day)
  end
4

2 回答 2

1

I don't understand, the model shouldn't have to look at params[:reschedule] to know if it's "simply a change to the remind_at time" -- the model is the thing being changed, it should be able to look at what's actually being changed and make sure it's only remind_at.

Looking at params[:reschedule] wouldn't be right even if you could easily do it -- as conceivably params[:reschedule] could be set at the same time other attributes were being modified, and you wouldn't want to allow that either. The only point to doing this in the model is not to trust the controller is doing the right thing (and has no security holes), but to ensure that only what's actually allowed is being done.

Which if I understand right, what's allowed is changing no attributes but remind_at, if created_at is past a certain time.

So what you really need to do is just look at what attributes have changed in a validation hook?

I believe the changed method should work to do that. It return a list of changed attributes since the last save. If the post is too old, you want to make sure they include include nothing but remind_at.

Does that work?

 if self.created_at > (Time.now-1.day) &&
    self.changed.find {|k| k.to_s != "remind_at"}
         # BAD, they're trying to save some other attribute changed
 end

http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changed

于 2015-03-19T18:37:30.457 回答
0

如果它的质量分配..然后在attr_accessible中包含该属性,或者在控制器或模型中显式设置它

于 2015-03-19T18:27:00.353 回答