How to set the following association:
class Midatum < ActiveRecord::Base
# ..., diagn1, diagn2, diagn3
# sample data:
# ..., "0123", nil ,"0124"
# ..., "0123", nil ,"0124"
# ..., "0123", "1123", nil
belongs_to :icd9, :foreing_key => :diagn1
belongs_to :icd9, :foreing_key => :diagn2
belongs_to :icd9, :foreing_key => :diagn3
end
class icd9 < ActiveRecord::Base
# icd9, description
# sample data:(unique)
#"0123", "some text"
#"0124", "some other text"
#"1123", "description text"
#"1133", "description text"
has_many :midata, :foreing_key => :icd9, :primary_key => :icd9
end
This does not work. It may be obvious for someone but not for me. The database
is a legacy DB and readonly. I need to establish this assoc to able to work with the data.
This answer comes from a Rails expert and it does solve my problem. I am posting it in case someone else have the same problem.
belongs_to :icd9_a, :foreign_key => :diagn1, :class_name => "Icd9"
belongs_to :icd9_b, :foreign_key => :diagn2, :class_name => "Icd9"
belongs_to :icd9_c, :foreign_key => :diagn3, :class_name => "Icd9"
But that means you'll need to query the association using all three methods:
m = Midatum.first
m.icd9_a
m.icd9_b
m.icd9_c
In the same way, over in the Icd9 class you'll need three separate associations with unique names:
class Icd9 < ActiveRecord::Base
self.primary_key = :icd9
has_many :midata_a, :foreign_key => :diagn1, :class_name => "Midatum"
has_many :midata_b, :foreign_key => :diagn2, :class_name => "Midatum"
has_many :midata_c, :foreign_key => :diagn3, :class_name => "Midatum"
end
Note also that since the icd9 table doesn't have an 'id' column but uses the 'icd9' column as the primary key, you'll need to set it as I've done:
self.primary_key = :icd9
Related
Hi I have a normal setup of Paperclip and S3 for image uploads in my application, this is the model I use for attachments:
class Picture < ActiveRecord::Base
belongs_to :ofert, dependent: :destroy
has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100>", :large => "600x400#", :morethumb => "50x50#", :ultrathumb => "25x25#" },
:default_url => "https://s3-sa-east-1.amazonaws.com/:s3_bucket/ofert_defaults/:style/brown_hat.jpg"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
validates_attachment_presence :image, :if => :isProduction?
validates_attachment_size :image, :less_than => 5.megabytes
#process_in_background :image, processing_image_url: 'https://s3-sa-east-1.amazonaws.com/:s3_bucket/ofert_defaults/:style/brown_hat.jpg'
end
The above works very well, however, when I try to destoy a picture:
picture.destroy
I get the following error: stack level too deep
but if instead I do the following:
picture.delete
It works, however the above only deletes the record but not the file uploaded to my S3 bucket, any idea?
It is a bug in rails. Read here
Using
belongs_to :ofert, dependent: :destroy
will cause a circular loop (assuming you have a similar line in the associated model 'Ofert' as well)
You can try replacing it with dependent :delete in one of these models or write after_destroy methods in both to manually destroy the associated model.
Read this discussion here on stackoverflow
I am having some weird behavior in a Rails model and I'm not quite sure why. Thanks to anyone who can point me as to what I'm missing or not understanding.
The Problem
I have a model Car with a has_many :through relationship on Part through CarsPart. I expect accessing a car's parts to be in alphabetical order. I created the model specs and the controller specs. In the controller, the parts are ordered in alphabetical order as called out in the has_many relationship. In the controller spec, they are in order. In the model spec, they are not. I don't think it's tied to the testing framework because i've debugged the running server and see the same behavior.
The Code
Car
class Car < ActiveRecord::Base
has_many :cars_parts
has_many :parts, -> { order('name asc') }, through: :cars_parts, :dependent => :destroy
accepts_nested_attributes_for :cars_parts, :allow_destroy => true
validates :make, :model, presence: true
validate :validate_cars_parts
def validate_cars_parts
errors.add(:parts, "wrong number") if self.cars_parts.size < 1
self.cars_parts.each do |car_part|
part = Part.find(car_part.part_id)
errors.add(:parts, "doesn't exist") if part == nil
end
end
end
Part
class Part < ActiveRecord::Base
belongs_to :cars_part
has_many :cars, through: :cars_parts
validates :name, presence: true
end
CarsPart
class CarsPart < ActiveRecord::Base
belongs_to :car
belongs_to :part
end
Cars Controller Spec Passes
require 'rails_helper'
RSpec.describe CarsController, type: :controller do
render_views
context 'property features' do
describe "GET #show/id returns ordered parts" do
before :each do
#p4 = FactoryGirl.create(:part, :name => 'BPart2')
#p3 = FactoryGirl.create(:part, :name => 'APart2')
#p6 = FactoryGirl.create(:part, :name => 'BPart3')
#p5 = FactoryGirl.create(:part, :name => 'APart3')
#p2 = FactoryGirl.create(:part, :name => 'BPart1')
#p1 = FactoryGirl.create(:part, :name => 'APart1')
end
it 'returns parts in alphabetical order' do
car = FactoryGirl.create(:car, make: 'Nissan', model: 'Murano', parts: [#p4, #p3, #p6, #p5, #p2, #p1])
get :show, id: car.id, format: :json
expect(response).to have_http_status(:success)
expect(response).to render_template(:show)
response_json = JSON.parse(response.body)
response_json['parts'].each do |part|
puts part['id']
end
expect(response_json['parts'].size).to eq(6)
expect(response_json['parts'][0]['id']).to eq(#p1.id)
expect(response_json['parts'][1]['id']).to eq(#p3.id)
expect(response_json['parts'][2]['id']).to eq(#p5.id)
expect(response_json['parts'][3]['id']).to eq(#p2.id)
expect(response_json['parts'][4]['id']).to eq(#p4.id)
expect(response_json['parts'][5]['id']).to eq(#p6.id)
end
end
end
end
Car Model Spec Fails
require 'rails_helper'
RSpec.describe Car, type: :model do
context 'car parts' do
before :each do
#p4 = FactoryGirl.create(:part, :name => 'BPart2')
#p3 = FactoryGirl.create(:part, :name => 'APart2')
#p6 = FactoryGirl.create(:part, :name => 'BPart3')
#p5 = FactoryGirl.create(:part, :name => 'APart3')
#p2 = FactoryGirl.create(:part, :name => 'BPart1')
#p1 = FactoryGirl.create(:part, :name => 'APart1')
end
it 'returns parts in alphabetical order' do
car = FactoryGirl.create(:car, make: 'Nissan', model: 'Murano', parts: [#p4, #p3, #p6, #p5, #p2, #p1])
expect(car).to be_valid
expect(car.errors.messages.size).to eq(0)
expect(car.parts.size).to eq(6)
car.parts.each do |part|
puts part.id
end
expect(car.parts[0]['name']).to eq('APart1')
expect(car.parts[1]['name']).to eq('APart2')
expect(car.parts[2]['name']).to eq('APart3')
expect(car.parts[3]['name']).to eq('BPart1')
expect(car.parts[4]['name']).to eq('BPart2')
expect(car.parts[5]['name']).to eq('BPart3')
end
end
end
Summary
Please help me understand why when accessing them through the model they are not ordered, but when the controller looks them up and renders them, they are.
Thank you.
EDIT
The only way I have managed to get this to work is to create a 'ordered_parts' method that does the ordering and remove the order from the has_many. I had to change all my controllers to call 'ordered_parts' instead of the 'parts' method. Surely there is a better way. If anyone knows, please help.
def ordered_parts
self.parts.order('name asc')
end
Let me explain first my model structure:
i have a status model:
class Status
include Mongoid::Document
include Mongoid::Search
include Mongoid::Timestamps
field :status_code, type: Integer
field :status_description, type: String
validates :status_code, :status_description, :transactiontype, :presence => true
belongs_to :transactiontype, :class_name => 'Transactiontype'
has_many :transactions, :class_name => 'Transaction', autosave: false
search_in :status_code, :status_description, :transactiontype => :transaction
def self.getStatus(transactiontype)
statuses = Status.where(:transactiontype_id => transactiontype).all
stats = []
puts "DATE DASHBOARD: #{Time.now.beginning_of_day} to #{Time.now.end_of_day}"
statuses.each do |status|
transactions = status.transactions.dateRange(Date.today.beginning_of_day, Date.today.end_of_day)
if transactions.length > 0
status.transactions = transactions
stats.push(status)
end
end
puts "SIZE : #{stats.size}"
stats
end
etc..
end
then i have another model called transactions:
class Transaction
include Mongoid::Document
include Mongoid::Search
include Mongoid::Timestamps
field :ref_no, type: String
field :trans_date, type: DateTime
belongs_to :status, :class_name => 'Status'
belongs_to :transactiontype, :class_name => 'Transactiontype'
validates :ref_no, :trans_date, :status, :presence => true
def self.dateRange(startdate,enddate)
puts "DATE : #{startdate} to #{enddate}"
if !startdate.blank?
where(:created_at => {"$gt" => startdate.beginning_of_day, "$lt" => enddate.end_of_day})
# where(:trans_date.gte => startdate.beginning_of_day, :trans_date.lte => enddate.end_of_day)
end
end
etc..
end
the weird part is that:
when im trying to execute:
Status.getStatus(params[:transactiontype_id])
i received the correct output but the transactions associated with the Status is being updated and each records before the filtered date is being updated with null status_id.
i already tried to add autosave: false but nothing works
can someone help me with this?
the solution is to convert the active record to json first
def self.getStatus(transactiontype)
statuses = Status.where(:transactiontype_id => transactiontype).all
stats = []
puts "DATE DASHBOARD: #{Time.now.beginning_of_day} to #{Time.now.end_of_day}"
statuses.each do |status|
ar_status = status.as_json
ar_status['transactions'] = status.transactions.dateRange(Date.today.beginning_of_day, Date.today.end_of_day)
if ar_status['transactions'].length > 0
stats.push(ar_status)
end
end
puts "SIZE : #{stats.size}"
stats
end
for some reason.. its auto saving the records.
I initiated the test environment in my rails app, and when I test the user model with the default code, it throws the following error:
Test code:
test "the truth" do
assert true
end
1) Error:
UserTest#test_the_truth:
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry '' for key 'index_users_on_email': INSERT INTO `users` (`created_at`, `updated_at`, `id`) VALUES ('2014-02-01 17:45:51', '2014-02-01 17:45:51', 298486374)
and inside my user model, I have the following associations
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :user_name , :email, :first_name ,:last_name , :presence => true
has_many :invitations
has_many :incoming_friends, -> { where(:status => '1') }, :class_name => "User", :foreign_key => "friend_id", :through => :invitations
has_many :outgoing_friends, -> { where(:status => '1') }, :class_name => "User", :foreign_key => "user_id", :through => :invitations
Firstly, check your user model fixture in test/fixtures/users.yml. If you have empty declarations of one and two:
one: {}
# column: value
#
two: {}
# column: value
it can cause a problems, because there is a lack of attributes. Remove this part or comment it:
#one: {}
# column: value
#
#two: {}
# column: value
And try run it again.
I've been jumping between design patterns, firstly trying polymorphic, now landing on STI. The main goal is to implement a Server > Host > Guest model where a Server has Hosts, Hosts have Guests and each able to have Posts. Although not the main purpose of the question any ideas in the design matter would be helpful as this is my first rails or ruby project.
What I have now is:
class Device
has_may :children, :class_name => "Device", :foreign_key => "parent_id"
belongs_to :parent, :class_name => "Device"
has_many :posts
end
class Server,Host,Guest < Device
end
STI is used because Server,Host,Guest basically have the same attributes.
I'm having trouble setting up the routes and controllers so I could view a Server's children which would be of type Host or to create a new Server's Host.
First, a good thing would be to add the following things, making everything easier to use for you :
class Device < ActiveRecord::Base
has_many :children, :class_name => "Device", :foreign_key => "parent_id"
has_many :servers, -> { where type: "Server" }, :class_name => "Device", :foreign_key => "parent_id"
has_many :hosts, -> { where type: "Host" }, :class_name => "Device", :foreign_key => "parent_id"
has_many :guests, -> { where type: "Guest" }, :class_name => "Device", :foreign_key => "parent_id"
belongs_to :parent, :class_name => "Device"
has_many :posts
end
With that, you will be able to do server.hosts, etc, which is quite convenient.
Then, you should move each subclass (Server, Host, Guest) to its own file due to Rails loading system. You can try to access the model Server in the console, you will get an undefined error. To fix it, you need to load the model Device, or simply move each subclass in a different file.
Finally, for the routing/controller part, I will advise you to read this post I wrote about common controller for STI resources : http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-2/.
Note that this is the second part, for more details check out the other articles.