Odoo 11 Development Essentials(Third Edition)
上QQ阅读APP看书,第一时间看更新

Row-level access rules

We can find the Record Rules option in the Technical menu, alongside Access Control List.

Record rules are defined in the ir.rule model. As usual, we need to provide a distinctive name. We also need the model they operate on and the domain filter to use for the access restriction. The domain filter uses the usual list of tuples syntax used across Odoo. We will be explaining this Domain Expression syntax in Chapter 7, Business Logic - Supporting Business Processes.

Usually, rules apply to some particular security groups. In our case, we will make it apply to the Employees group. If it applies to no security group in particular, it is considered global (the global field is automatically set to True). Global rules are different because they impose restrictions that non-global rules can't override.

To add the record rule, we should create a security/todo_access_rules.xml file with the following content:

<?xml version="1.0" encoding="utf-8"?> 
<odoo> 
  <data noupdate="1"> 
    <record id="todo_task_user_rule" model="ir.rule"> 
      <field name="name">ToDo Tasks only for owner</field> 
      <field name="model_id" ref="model_todo_task"/> 
      <field name="domain_force">
          [('create_uid','=',user.id)] 
      </field> 
      <field name="groups" eval="
      [(4,ref('base.group_user'))]"/> 
    </record> 
  </data> 
</odoo> 
Notice the noupdate="1" attribute. It means this data will not be updated in module upgrades. This will allow it to be customized later since module upgrades won't destroy user-made changes. But be aware that this will also be the case while developing, so you might want to set noupdate="0" during development until you're happy with the data file.

In the groups field, you will also find a special expression. It's a one-to-many relational field, and they have a special syntax to operate with. In this case, the (4, x) tuple indicates to append x to the records, and here x is a reference to the Employees group, identified by base.group_user. This one-to-many writing special syntax is discussed in more detail in Chapter 4, Models – Structuring the Application Data

As before, we must add the file to __manifest__.py before it can be loaded into the module:

'data': [ 
  'security/ir.model.access.csv', 
  'security/todo_access_rules.xml', 
  'views/todo_menu.xml', 
  'views/todo_view.xml',
'views/res_partner_view.xml', ],

If we did everything right, we can run the module tests and now they should pass.