Using Question Mark Character in Rails/Activerecord Column Name

Using question mark character in Rails/ActiveRecord column name

Rails will automatically generate the method smart? if there is a field named 'smart'.

In Rails' ActiveRecord, what does a question mark at the end of a method name corresponding to a column do?

It will return true if a field is present? or not. So an empty string "" will return false.

Why do we need question mark in this rails try block?

Ruby is somewhat unusual in that it lets you include a wide range of characters in the names of methods including ? and !.

They have no special significance to the interpreter but the language convention is that:

  • methods ending with ? are interrogative - they should ALWAYS return true or false.
  • methods ending with ! either mutate the object the are called on or may raise a exception.

So why does it matter at all? In this particular case it does not matter since your user class has an accessor for the @admin instance variable created by ActiveRecord - just like any other column.

If it did not however current_user.try(:admin) would always return nil. Remember that instance variables are always private in Ruby until you provide an accessor*.

# Just a plain old Ruby class - not an ActiveRecord model 
class User
def initialize
@admin = true
end

def admin?
@admin
end
end

User.new.try(:admin) # is always nil...

This is because User does not respond to :admin and .try prevents a NoMethodError and just returns nil instead.



ActiveRecord and accessors:

In a plain old ruby class you would add accessors to make the instance variable @admin available:

class User
def initialize
@admin = true
end

attr_accessor :admin
end

Which does this:

class User
def initialize
@admin = true
end

# getter
def admin
@admin
end

# setter
def admin=(val)
@admin = val
end
end

ActiveRecord reads the schema from your database and uses metaprograming to auto-magically add accessors to your model classes. They are a bit more complex than the example above but its the same basic principle. Thats why your User model responds to #admin.

Rails: how do I use question marks in a model?

It's most likely a Mongoid bug as question marks in field names are valid in MongoDB. If I had to take a guess, it could be a weird conflict with the automatic <field>? that are created by Mongoid.

The easiest way to work around this would be to try accessing it through the raw hash that is pulled out from MongoDB, you can access it with model.attributes["failed?"]. If you still have issues, then likely it's a MongoDB driver problem.

Rails Form Helper not reading question mark for object attribute

? is not a valid character for inclusion within a column name. First, create a new database migration:

# from command line
rails generate migration ChangeCorrectInAnswers

Rename your column from correct? to correct:

# in the resulting migration
class ChangeCorrectInAnswers < ActiveRecord::Migration
def up
rename_column :answers, :correct?, :correct
end
end

Run the migration:

# from command line
rake db:migrate

Finally, remove the ? from your field in the view:

# app/views/questions/_form.html.erb
<%= answer.check_box :correct %>

Find model records by column names in the order the array given

By default, Rails query will sort the records by their ids. If you want to remain the order as the value fields, try to the following code.

user_ids = [5,4,2,1]
Project.where(user_id: user_ids).order("FIELD(user_id, #{user_ids.join(',')})").pluck(:user_id)

How can I get the column name and value for an ActiveRecord association?

#column_names is a method that gets all of an AR's column names in string form.

.collect(&:to_sym) calls to_sym on each one of these and puts them in an array.

column_names = Feature.column_names.collect(&:to_sym)
@products.features.each do |feature|
#iterate thru column names. btw string interpolation is better than using +
column_names.each { |column| puts "#{column} : #{feature.send(column)}" }
end

Retrieving Rails Model Column Names

User.column_names

Like a lot of things in Rails, it just works :)

Rails create table from csv that has special character in column name

You can't have parentheses in a column name: Rails will try to map the column name "BW (MB)" to a valid Ruby attribute name, and parentheses aren't allowed. Spaces convert to underlines OK, but parentheses aren't allowed.

Look at how Active Record does convention over configuration - one of the key principles of Rails.

Rails lets you do some amount of overriding, but you can't have a column "BW (MB)" that equates to a valid Ruby class attribute.

You have 2 options - both of which you need to change the column name to "BW".

Option 1: edit the headers of the CSV files so they match the column name, and change your code accordingly.

Option 2: leave the header as-is, but write additional code to replace the hash key "BW (MB)" with "BW"

CSV.foreach(csv_file, :headers => true) do |row|
foo = row.to_hash.slice('Date', 'Market Area', 'BW (MB)')
foo["BW"] = foo["BW (MB)"]
foo.delete("BW (MB)")
Sevonedatum.create!(foo)
end

(you can optimize that to fewer lines - I'm making it verbose since you've said you're a beginner)



Related Topics



Leave a reply



Submit