On Wednesday, January 22, 2020 at 10:59:21 AM UTC-8, Javier Valencia wrote:
>
> Hello everyone, I'm having a weird behaviour with Sequel at the moment.
>
> In my sqlite, I have an string field where I can also store integers 
> (alphanumeric). The problem is, when I get the Sequel Model to read an 
> entry, that String field is casted into an Integer if the field contained 
> an integer (it works for strings though).
>
> I mean, if the field is "abcde", then it's casted as String.
> If the field contains "12345", it's casted as an Integer, even though the 
> field type is string in the database.
>
> I need that Integer to stay as an String.
>
> This is how I created the database:
>
> create_table(:topics) do
>    primary_key :id
>    column :name, :string, null: false
>    unique :name
> end
>
>
> This is the model:
>
> class Topic < Sequel::Model
> end
>
>
> Part of the code that shows the bug (sinatra app):
>
> get "/topic/:topic_name" do
>    topic = Topic.first(name: params[:topic_name])
>    puts topic.name.class  # <-- outputs Integer for "12345"
>     ....more code....
> end
>
>
> The result is this (it shows capitalize error because the view tries to 
> capitalize the string after the "puts" output):
> Integer
> 2020-01-22 18:44:45 - NoMethodError - undefined method `capitalize' for 
> 123:Integer:
>     /home/tigre/files/code/ruby/pb/views/index.erb:20:in `
> __tilt_47427256009060'
>     /var/lib/gems/2.5.0/gems/tilt-2.0.10/lib/tilt/template.rb:170:in `call'
>     /var/lib/gems/2.5.0/gems/tilt-2.0.10/lib/tilt/template.rb:170:in 
> `evaluate'
>     /var/lib/gems/2.5.0/gems/tilt-2.0.10/lib/tilt/template.rb:109:in `
> render'
>     /var/lib/gems/2.5.0/gems/sinatra-2.0.8.1/lib/sinatra/base.rb:834:in 
> `render'
>     /var/lib/gems/2.5.0/gems/sinatra-2.0.8.1/lib/sinatra/base.rb:682:in 
> `erb'
> .......
>
>
> So, it outputs Integer instead of String. I'd like to know how to fix 
> this. May be force the model to treat that field as string?
>
> Thank you in advance.
>

Use:

column :name, String, null: false

This will use the appropriate string type for the database. SQLite does not 
recognize a type named "string", so it does not use TEXT affinity for the 
column. See https://www.sqlite.org/datatype3.html

In general, SQLite's type system is quite limited and much more permissive 
than other database type systems.  That's one of the things you should 
consider when deciding whether to use it.

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sequel-talk/3c23537a-4fee-4e57-8ab9-1caaf68dadfe%40googlegroups.com.

Reply via email to