" /> " /> "/>

ir.rule with a related field, only working with new records [Odoo v8]

103 Views Asked by At

I have this ir.rule. I want a group only see their own records on account.voucher.

<record id="ir_rule_account_voucher_restrictions" model="ir.rule">
    <field name="name">Voucher Restrictions</field>
    <field name="model_id" ref='model_account_voucher'/>
    <field name="groups" eval="[(4, ref('group_users_restrictions'))]"/>
    <field name="domain_force">[('user_id', '=', user.id)]</field>
</record>

account.voucher didn't have a user_id field, so I have to create it now. The only way I have to recover the older user_id is with message_follower_ids field, so I have this new field

class AccountVoucher(models.Model):
    _inherit = 'account.voucher'

    user_id = fields.Char(string='Salesperson', related="message_follower_ids.name", store=True)

And it's working OK with the new records I'm creating, but I also need the old records to make the ir.rule work

The first record is the one I've created

I think the problem is the same with computed fields, they don't get stored on db. How should I add to accomplish my task?

1

There are 1 best solutions below

0
icra On

message_follower_ids is a Many2many field. Relating user_id as Char field might be inconsistent.

I'm not sure comparing name with user.id would work. Consider storing id field instead.

Also you are storing .name field so this would return an error in case there should be multiple followers.

To recompute fields in Odoo v8 you can use server actions:

model = env['account.voucher']
object = model.search([])
env.add_todo(model._fields['user_id'], object)
model.recompute()

You can anyway avoid creating a related field because message_follower_ids is already present in your model (since you are inheriting mail_thread)

So your domain can be semplified:

<field name="domain_force">[('message_follower_ids', 'in', [user.id])]</field>

Note i'm using in operator since message_follower_ids is parsed as a list of ids, so correct operation is to check if message_follower_ids contains your current logged in user.id

In my advice, best practice would be to have a real relation (not based on message_follower_ids) in account.voucher model.

class AccountVoucher(models.Model):
    _inherit = 'account.voucher'

    user_id = fields.Many2one(
      string='Salesperson',
      comodel_name="res.users",
      default=lambda self: self.env.user.id
    )

Then migrate (manually or via script) previous records.

for acc_id in self.env['account.voucher'].search([('user_id', '=', False]):
  acc_id.write({'user_id': acc_id.message_follower_ids[0].id})

If you're going to use odoo shell, don't forget to:

self.env.cr.commit()