On May 19, 10:33 pm, Nurahmadie <[email protected]> wrote:
> I have this model
>
> class User < Sequel::Model(:users)
>    one_to_many :ftp_logs
> end
>
> this migration file
>
> class AddNewUser < Sequel::Migration
>   def up
>     create_table :users do
>        primary_key :id
>        varchar :username
>        varchar :password
>     end
>   end
>   def down
>     drop_table :users
>   end
> end
>
> class CreateAdmin < Sequel::Migration
>   def up
>     password = myhelper.rndstr 8
>     User.create(:username => "admin", :password => password)
>     puts "your admin password is : " + password
>   end
>   def down
>     user = User[:username => "admin"]
>     user.destroy
>   end
> end

There are a couple of problems. First, each migration should be in a
separate file. Second, you should not use models in your migrations.
While it's possible to do so, it's a bad idea, so if you don't know
how to do it correctly, you shouldn't attempt to do so.  Do the
following instead

class CreateAdmin < Sequel::Migration
  def up
    password = myhelper.rndstr 8
    DB[:users].insert(:username => "admin", :password => password)
    puts "your admin password is : " + password
  end
  def down
    DB[:users].filter(:username => "admin").delete
  end
end

If you have any callbacks in your User model, just recreate them in
your migration.

> My problem is the CreateAdmin will raise error on User.create saying
> that method username= doesn't exist or access is restricted to it.

Expected as the models are loaded before the first migration is run,
when the table doesn't exist and thus the username column doesn't
exist.

> But when I check the column before create, with something like this
>
> User.columns == [:id, :username, :password]
>
> or just print out the column with
>
> puts User.columns
>
> right before create. The migration will be succeed...
>
> is there something I miss? or is that a bug?

Calling columns before attempting to create a new object will cause
the model class to recognize that it doesn't know the columns, attempt
to load them from the database, and create the column accessors at
that point.  However, you avoid the problem entirely if you just use
plain datasets in your migrations, which is the recommended approach.

Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sequel-talk?hl=en.

Reply via email to