Rails锁定'已完成''todo'

时间:2016-02-05 14:12:25

标签: ruby-on-rails validation

我有一个带有{ "name": "Boilerplate", "version": "0.0.1", "description": "A boilerplate to quickly get started with an offline first React/Redux app", "repository": { "type": "git", "url": "https://github.com/OskarKlintrot/Offline-First-React-And-Redux-Boilerplate" }, "scripts": { "start": "webpack-dev-server", "build": "webpack --progress --colors --production" }, "private": true, "devDependencies": { "babel-core": "^6.2.1", "babel-eslint": "^4.0.5", "babel-loader": "^6.2.0", "babel-polyfill": "^6.2.0", "babel-preset-es2015": "^6.1.18", "babel-preset-react": "^6.1.18", "babel-preset-stage-1": "^6.1.18", "eslint": "^1.1.0", "eslint-loader": "^1.0.0", "eslint-plugin-react": "^3.13.1", "file-loader": "^0.8.5", "history": "^1.17.0", "react": "^0.14.2", "react-dom": "^0.14.2", "react-hot-loader": "^1.3.0", "react-mdl": "^1.0.2", "react-redux": "^4.0.4", "react-router": "^1.0.2", "react-tap-event-plugin": "^0.2.1", "redux": "^3.0.5", "redux-devtools": "^3.0.0", "redux-devtools-dock-monitor": "^1.0.1", "redux-devtools-log-monitor": "^1.0.1", "redux-history-transitions": "^1.0.0", "redux-thunk": "^1.0.2", "transfer-webpack-plugin": "^0.1.4", "webpack": "^1.12.9", "webpack-dev-server": "^1.14.0" } } title:string, description:text的Todo模型和两个自我参考:儿童&父母通过todos_todos表(parent_id,child_id)加入。

除非用户通过completed:boolean,否则我希望阻止编辑completed == true的待办事项。如果完成,我还想防止孩子被添加到待办事项中。

我知道我可以在控制器中轻松完成此操作:

params[:completed] = false

...但我不确定这是否正确。我觉得我应该在模型中使用验证,除非我无法找到与用户输入相比较的模型中的现有数据。

2 个答案:

答案 0 :(得分:1)

验证它,但最重要的是阻止用户首先进行不必要的更改。这意味着这些限制是在界面中实现的。例如,当您渲染todo时,您可以渲染锁定或解锁版本(允许更多内容)。他们可以更新“锁定”状态,这将重新加载页面(如果你通过ajax执行,则重新加载div)然后他们将看到另一个版本。

这一切都非常广泛和普遍,但你的问题也是如此。

答案 1 :(得分:1)

只需使用authorization(最好使用CanCanCan):

#Gemfile
gem "cancancan"

#app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    cannot :manage, Todo, completed: true
  end
end

#app/controllers/todos_controller.rb
class TodosController < ApplicationController
  laod_and_authorize_resource
end

这将阻止与上述记录的任何交互,除非您在Ability类中明确定义(可能有admin个用户可以做事等。)