How can I add values to string field in database from multiple select.
I have field in database:
t.string "types"
and view:
<%= f.select :order, [["One", 1], ["Two", 2], ["Three", 3]], {}, { :class => 'form-control', :multiple => true } %>
Maybe serialize or json is goot idea? Is it possible save and simple way read this?
You can use rails serialize on the column:
serialize :order, Hash
Or for JSON (depending what you want to do with it):
serialize :order, JSON
However, the columns needs to be of type 'text' not 'string' for serialize to work, so be sure to create a migration to change the column type.
rails g migration change_order_type_in_table_name
class ChangeOrderTypeInTableName < ActiveRecord::Migration
def up
change_column :my_table, :order, :text
end
def down
change_column :my_table, :order, :string
end
end
You can pass a class to serialize:
class User < ActiveRecord::Base
serialize :order, Array
end
The above ensures that order as an Array:
User.new
#=> #<User id: nil, order: [], created_at: nil, updated_at: nil>
Note that you might have to convert existing fields if the types don't match.
I have user model
class User
include MongoMapper::Document
key :phone, Integer, :required => true, :unique => true
key :is_confirmed, Boolean, :default => false
timestamps!
end
and validate uniqueness of phone but i can create user with the same phone without error.WHY?
why validate uniqueness doesn't work
MongoMapper uses ActiveModel:Validations, so it works almost exactly like ActiveRecord
Try this to validate: validates_uniqueness_of
validates_uniqueness_of :phone
Validations are run when attempting to save a record. If validations fail, save will return false.
Most Simple Validations can be declared along with the keys.
Example:
class Person
include MongoMapper::Document
key :first_name, String, :required => true
key :last_name, String, :required => true
key :age, Integer, :numeric => true
key :born_at, Time
key :active, Boolean
key :fav_colors, Array
end
The available options when defining keys are:
:required – Boolean that declares validate_presence_of
:unique – Boolean that declares validates_uniqueness_of
:numeric – Boolean that declares validates_numericality_of
:format – Regexp that is passed to validates_format_of
:in – Array that is passed to validates_inclusion_of
:not_in – Array that is passed to validates_exclusion_of
:length – Integer, Range, or Hash that is passed to validates_length_of
I have an application which relies heavily on the hstore type in postgres. The Issue I can't seem to get over is making the hstore searchable in sunspot. Here is some code I am working on
class Post < ActiveRecord::Base
# properties is type hstore
%w[price condition website].each do |key|
store_accessor :properties, key
end
...
searchable :auto_index => false, :auto_remove => false do
text :title, :boost => 5.0
integer :category
integer :subcategory
# this is whats giving me the problem
string :properties["price"]
end
end
I have tried adding different types but nothing seems to work. Is this a feature not yet supported?
Hstore is basically a hash it stores keys and values so all you have to do is iterate over the the keys and look them up.
Here is the working code:
searchable :auto_index => false, :auto_remove => false do
text :title, :boost => 5.0
integer :category
integer :subcategory
%w[price condition website].each do |key|
string key.to_sym do
properties[key]
end
end
end
hopefully in the future they'll have support for
hstore :properties
I'm using DataMapper in Rails, replacing ActiveRecord and am trying to do some single table inheritance. The problem is, sqlite3 seems to be reading all of my inherited tables weird, and so I get some strange errors when trying to create an instance of that table in ruby.
I am using a model, ServerFile, to represent any uploaded or generic file that I want instanced in my database. I have another model, Upload, that extends that and represents an Upload from a user. I have two more models extending from ServerFile, Thumbnail, and UploadThumbnail, to represent a generic Thumbnail and a Thumbnail for an upload accordingly.
The error I keep getting is DataObjects::IntegrityError (server_files.upload_id may not be NULL) when I try to create an instance of an Upload like this:
upload = Upload.new(
filename: uploaded_io.original_filename,
path: path.to_s,
content_type: uploaded_io.content_type,
token: rand_token())
upload.member = #member
upload.title = params[:title]
upload.description = params[:description]
upload.save
And here are my models:
class ServerFile
include DataMapper::Resource
property :id, Serial
property :token, String, unique_index: true
property :filename, String
property :path, Text, unique: true
property :content_type, Text, length: 5..200
property :type, Discriminator
property :created_on, Date
property :created_at, DateTime
property :updated_on, Date
property :updated_at, DateTime
end
class Upload < ServerFile
property :title, String
property :description, Text
has n, :topics, through: Resource
has n, :subjects, through: Resource
has n, :downloads
has n, :comments, 'UploadComment'
has n, :ratings, 'UploadRating'
belongs_to :member
has 1, :thumbnail, 'UploadThumbnail', required: false
end
class Thumbnail < ServerFile
##IMAGE_EXTENSIONS = [:'png', :'jpg', :'jpeg', :'gif', :'svg', :'cgm']
validates_with_method :filename, :is_valid_image?
def is_valid_image?
##IMAGE_EXTENSIONS.each do |ext|
return true if /[\w\d\.\_\-]+\.#{ext.to_s}/ =~ #filename
end
[false, 'Invalide image type.']
end
end
class UploadThumbnail < Thumbnail
belongs_to :upload
end
And here is my sqlite schema for the table 'server_files' (and btw, when I list my tables, 'uploads' isn't listed among them):
sqlite> .schema server_files
CREATE TABLE "server_files" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "token" VARCHAR(50), "filename" VARCHAR(50), "path" TEXT, "content_type" TEXT, "type" VARCHAR NOT NULL, "created_on" DATE, "created_at" TIMESTAMP, "updated_on" DATE, "updated_at" TIMESTAMP, "title" VARCHAR(50), "description" TEXT, "member_id" INTEGER NOT NULL, "upload_id" INTEGER NOT NULL);
CREATE UNIQUE INDEX "unique_server_files_path" ON "server_files" ("path");
CREATE UNIQUE INDEX "unique_server_files_token" ON "server_files" ("token");
There is no need for an upload_id column on the server_files table. Because Upload inherits from ServerFile, this would essentially be self-referential. The column type with type Discriminator will be set to Upload in the database when the model is successfully saved. That being said, if you want to set a custom upload_id anyways, you can do it with a callback like this:
before :create, :generate_upload_id
def generate_upload_id
generated_upload_id = <do something>
attribute_set(:upload_id, generated_upload_id) unless upload_id
end
Otherwise, simply write a migration that removes the upload_id column from the server_files table
Source: http://datamapper.org/docs/misc.html
DataMapper for some reason just didn't like my superclass ServerFile. When I broke it up, it worked perfectly! (:
class Upload < ServerFile
include DataMapper::Resource
property :id, Serial
property :token, String, unique_index: true
property :filename, String
property :path, Text, unique: true
property :content_type, Text, length: 5..200
property :created_on, Date
property :created_at, DateTime
property :updated_on, Date
property :updated_at, DateTime
property :title, String
property :description, Text
has n, :topics, through: Resource
has n, :subjects, through: Resource
has n, :downloads
has n, :comments, 'UploadComment'
has n, :ratings, 'UploadRating'
belongs_to :member
has 1, :thumbnail, 'UploadThumbnail', required: false
end
class Thumbnail < ServerFile
include DataMapper::Resource
property :id, Serial
property :token, String, unique_index: true
property :filename, String
property :path, Text, unique: true
property :content_type, Text, length: 5..200
property :type, Discriminator
property :created_on, Date
property :created_at, DateTime
property :updated_on, Date
property :updated_at, DateTime
##IMAGE_EXTENSIONS = [:'png', :'jpg', :'jpeg', :'gif', :'svg', :'cgm']
validates_with_method :filename, :is_valid_image?
def is_valid_image?
##IMAGE_EXTENSIONS.each do |ext|
return true if /[\w\d\.\_\-]+\.#{ext.to_s}/ =~ #filename
end
[false, 'Invalide image type.']
end
end
class UploadThumbnail < Thumbnail
belongs_to :upload
end
I've been doing a spike on Rails 3 and Mongoid and with the pleasant memories of the auto scaffolding in Grails I started to look for a DRY view for ruby when I found:
http://github.com/codez/dry_crud
I created a simple class
class Capture
include Mongoid::Document
field :species, :type => String
field :captured_by, :type => String
field :weight, :type => Integer
field :length, :type => Integer
def label
"#{name} #{title}"
end
def self.column_names
['species', 'captured_by', 'weight', 'length']
end
end
But since dry_crud depends on self.column_names and the class above doesn't inherit from ActiveRecord::Base I have to create my own implementation for column_names like the one above. I would like to know if it possible to create a default implementation returning all of the fields above, instead of the hard coded list?
Why would you go through the trouble of doing all that when there's an in-built method?
For Mongoid:
Model.attribute_names
# => ["_id", "created_at", "updated_at", "species", "captured_by", "weight", "length"]
Short of injecting a new method in Mongoid::Document you can do this in your model.
self.fields.collect { |field| field[0] }
Update : Uhm better yet, if you fell adventurous.
In the model folder make a new file and name it model.rb
class Model
include Mongoid::Document
def self.column_names
self.fields.collect { |field| field[0] }
end
end
Now your model can inherit from that class instead of include Mongoid::Document. capture.rb will look like this
class Capture < Model
field :species, :type => String
field :captured_by, :type => String
field :weight, :type => Integer
field :length, :type => Integer
def label
"#{name} #{title}"
end
end
Now you can use this natively for any model.
Capture.column_names