undefined method `encrypted_latitude' for #<Location:0x007f574a4eef50> - ruby-on-rails

Hi I am using symmetric encryption (This one) gem to encrypt some fields. I have generated all the keys and followed all the steps given in it. But When I am trying to save data on my server it throws error on these lines
attr_encrypted :latitude
attr_encrypted :longitude
Error is
undefined method `encrypted_latitude' for #<Location:0x007f574a4eef50>
I have checked types, steps for gem and all looks fine.
Any idea what I am missing ...all works when I removed these lines from model. In Addition I have added attr_accessible for both fields and protected_attributes gem to make attr_accessible work
Any idea where I went wrong..Thanks

Looks like you may not have got a single instance of location. Do you have first at the end of the query?
i.e.
lat = Latitude.where( query ).first

The error means that the column named encrypted_latitude is not available in your locations table.
From the doc:
class User < ActiveRecord::Base
# Requires table users to have a column called encrypted_bank_account_number
attr_encrypted :bank_account_number

Related

ActiveRecord serialize not working properly with Hash column

I'm trying to store a Hash in a table column, using ActiveRecord's serialize method but I can't make it work. I'm using Rails 4.2.0 and RailsApi 0.3.1
This is my model:
class Agreement < ActiveRecord::Base
serialize :phone_numbers, Hash
end
phone_numbers is a text column like it's required.
Then in the console:
a = Agreement.new(phone_numbers: {"dario" => "12345"})
a.phone_numbers
=> "{\"dario\"=>\"12345\"}" #(Note this is a string, not a Hash as I would expect)
a.phone_numbers["dario"]
=> "dario" #(Not "12345" as I would expect)
Am I missing soemthing?? Thank you!
The behavior you're showing is consistent with the serialize call being wrong, either misnamed column, or missing entirely. Eg. https://gist.github.com/smathy/2f4536d3e59b7a52c855
You're showing the right code in your question, so either you didn't copy-paste that correctly, or perhaps it you haven't restarted your rails console since adding/correcting that serialize call?

Ruby on rails scaffold model validation questions

I am trying to follow a ruby on rails scaffold example.
I am using ruby version: 2.1.5 with rails version : 4.1.8
I have used this command:
rails generate scaffold User name:string email:string
This worked fine - I can run the example which shows crud functionality to my generated scaffold. The examples I have been following advise to look at the model file generated. The ones in the examples seemed to have a value called attr_accessible - but for me this was not generated - I do not know why - it seems to be quite useful so you can easily see what is inside your model? My model looks like this:
class User < ActiveRecord::Base
end
I altered it to look like this :
class User < ActiveRecord::Base
attr_accessible :name, :email
validates :name, :presence=>true
end
and when I now visit localhost/users I get the error:
Can somebody please tell me how a generated model can be created with this attr_accessible line, and how I can add an example of validation to the model.
Rails 4 doesn't use attr_accessible; it uses Strong Parameters.
They both serve as a guard for mass assignment of params, often times used during form submissions.
The scaffold doesn't support automatically setting strong params as far as I'm aware, in part because people implement strong params white listing very differently.
A couple more links on Strong Params
How is attr_accessible used in Rails 4?
https://github.com/rails/strong_parameters
https://github.com/elabs/pundit#strong-parameters <= I strongly recommend this gem
To me this suggests whatever guide you're following is out of date.
I think the problem is that the scaffolding that you have used is not compatible with how Rails works in later versions. In earlier versions of Rails, attr_accessible was used for preventing security problems related to mass assignment. In later versions, the countermeasure changed and moved to the controller instead of the model.
If you still want to use the attr_accessible macro, you can add gem 'protected_attributes' to your Gemfile and install with bundler.
You shouldn't add them in the model.
The stuff you wanna access goes into the controller, like
def index
#users = User.all
end
def show
#user = User.find(params[id])
end
...
private
def user_params
# It's mandatory to specify the nested attributes that should be whitelisted.
# If you use `permit` with just the key that points to the nested attributes hash,
# it will return an empty hash.
params.require(:user).permit(:name, :mail)
end
so you can use them afterwards in your views.
e.g. in app/views/users/show...
<h1>#user.name</h1>
<p>#user.email</p>

mongoid as_document error

I am using mongoid with devise invitable,
after assigning roles to user I found the following error
"**undefined method `as_document' for Array **" , any suggestions ?
invitable = find_or_initialize_with_error_by(:email, attributes[:email])
invitable.attributes = attributes
# scope_id attribute does not set properly
invitable.roles.map {|r| r.scope_id = attributes[:roles_attributes]["0"][:scope_id]}
if invitable.persisted? && !invitable.invited?
invitable.errors.add(:email, :taken)
elsif invitable.email.present? && invitable.email.match(Devise.email_regexp)
invitable.invite!
end
Whats wrong I am doing ?
This is likely because as_document doesn't work against an array, only single objects.
This is a bug with Mongoid and has_many relationships.
The method 'as_document' has to be defined for has_many relationships, like it is defined for embeds_many relationships.
I am going to make a pull request to have this issue fixed, in the meantime you can define mongoid in your gemfile like so:
gem 'mongoid', :git => https://github.com/mrjlynch.git
That happened to me with MongoId 5.1.0 when, in one direction I had "embeds_many", and in the other direction I had "belongs_to".
From what I know, the reverse of embeds_many shall be embedded_in.
Changing the reverse relationship to embedded_in fixed that issue for me.
I have to admit, this is a very obscure error message.

Audited audited_changes confusion

Im using collectiveidea's audited solution for auditing in rails.
So, there's a column (audited_changes) that is a TEXT definition in the database. When i retrieve an audit from the database, i get a plain string, and when i call that attribute in the view is non formated string. In the rdocs it says that theres a serialized hash of all changes. How can i get this hash? Also, in the same docs it says that there's access to old_attributes and new_attributes, how is this?
In my view:
<%= #audit.action %> # => update
<%= #audit.audited_changes %> # => --- name: - oldname - newname code: - oldcode - newcode
Or any chance on formatting this?
I think there might currently be a bug in audited. Are you using 3.0.0rc1? That is what I am using and I had something similar happen. First off, it didn't seem to recognize "Audit" as an ActiveRecord object, so I created an empty model in app/models/audit.rb. Once I did that I was seeing the behaviour you are seeing. To fix it, I removed the app/models/audit.rb and added an config/initializers/audited.rb with this in it:
include Audited::Adapters::ActiveRecord
This is an old question but I have an alternative answer that seems to be working well for me using Rails 4.2. Instead of using the initializer in the above answer I suggest keeping the model and adding "serialize :audited_changes" to the top.
class Audit < ActiveRecord::Base
belongs_to :user
serialize :audited_changes
end
You could use the built-in Audited::Audit model to query its data.
For example,
audit = Audited::Audit.last
audit.audited_changes # => {"name"=>["Steve", "Ryan"]}
"Steve" is the old value, "Ryan" is the new value. By default, the hash is stored in yaml format in the database.

How can I use ActiveRecord on a database that has a column named 'valid'? (DangerousAttributeError)

I am accessing a database that I can't change and it has a column named valid defined. Anytime I try to access an attribute, I get this exception:
valid? is defined by ActiveRecord
(ActiveRecord::DangerousAttributeError)
The exception makes sense, but since I'm not able to change the database, how can I get around this error?
I tried "overriding" the attribute, but I don't know how to remove the original column. I can successfully call this valid_column method, but any time I try to access another attribute defined in the database, I get the same exception. It still seems to be trying to map the valid column.
def valid_column=(valid)
write_attribute(:valid, valid)
end
def valid_column
read_attribute(:valid)
end
I'm not sure if it matters, but here are the details of my environment:
Windows Ruby 1.8.6
Informix database on a Linux server
activerecord (2.3.4)
activerecord-informix-adapter (1.0.0.9250)
ruby-informix (0.7.1)
Thanks in advance!
Try this:
class MyTable < AR:Base
class << self
def instance_method_already_implemented?(method_name)
return true if method_name == 'valid'
super
end
end
end
It's a hack, and it might not work in rails 3, but it could fix the problem for now.
I found it on the ruby on rails mailing list
If you wanted, you could also look at datamapper, which handles these sort of things somewhat more sanely.
Use safe_attributes - https://github.com/bjones/safe_attributes . It works perfectly out of the box:
class WebsiteUser < ActiveRecord::Base
establish_connection 'cf_website'
set_table_name 'nc_users'
bad_attribute_names :hash
end
Without worrying about ActiveRecord's reserved attributes, just add a gem in your gemfile and the gem will take care of name collisions automatically.
gem 'safe_attributes'
http://goo.gl/OO2H7
For reads you might be able to use SQL's select-as statement. Not sure if the following will work, but a default scope may make this easily do-able.
class MyRecord < ActiveRecord::Base
default_scope :select=> 'valid as valid_column'
end

Resources