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 に答える