简体   繁体   中英

Is there a way to create a MySQL table with a rails migration where the table doesn't have UPDATE permissions?

I'm looking to create a read-only table, and MYSQL permissions, I think, are the best way to do that.

Is this possible via a migration?

Generate a migration file as follows,

rails g migration add_permissions_to_table_name    
invoke  active_record
      create    db/migrate/20120620191050_add_permissions_to_table_name.rb

Edit the file as follows,

think@thinkComputer:~/Agile/ajax1$ vi db/migrate20120620191050_add_permissions_to_table_name.rb

class AddPermissionsToTableName < ActiveRecord::Migration
  def up

    execute "GRANT SELECT ON database1.table_name TO 'someuser'@'somehost'"

  end

  def down

    execute "REVOKE SELECT ON database1.table_name TO 'someuser'@'somehost'"

  end

end

Run the rake task as follows,

$ rake db:migrate

In future if you want to revoke that permission, then do,

$ rake db:migrate:down VERSION=20120620191050

You would want to be the a mysql user who has grant permissions on "database1.table_name", other wise you will get the following error,

mysql> GRANT SELECT ON database1.table_name TO 'someuser'@'somehost';
ERROR 1142 (42000): GRANT command denied to user 'current_mysql_user'@'localhost' for table 'table_name'

The details about the mysql user and database is located in "config/database.yml"

Please let me know if this works!

If you want to edit your models you can:

class YourModel < ActiveRecord::Base
  attr_readonly :your_field_name
end

It's not a migration but is probably the easiest way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM