Trying to build a one to one relationship between two preexisting models - ruby-on-rails

I am new to rails and I am trying to build a one to one relationship between two preexisting models (test and test_type) in rails.
Here is my workflow.
has_one :test_type - to tests model
belongs_to :test - to test_types model
rails g migration Add_Test_Type_To_Test test_type:references
rake db:migrate
Now that looks like it has worked ok but when I try to verify that it looks like it hasn't.
rails console
#type = TestTypes.new :name => "My Type"
#type.save
#test = Tests.new :name => "My Test"
TestTypes.find(1) //returns record ok
#test.test_type //returns nil
#test.test_type = TestTypes.find(1) //NameError: uninitialized constant Tests::TestType
#test.test_type //still nil
According to the output it finds my type in the database but it doesn't seem to be able to add it to my test class which indicates to me that the relationship is not working.
Is anybody able to tell what I am doing wrong?

Does it work if you just change one line of code belongs_to :test -> has_one :test to make it one-on-one relationship. But I think your error comes from the fact that you have not added test_type instance to test_type attribute of test object. So before making #test.test_type request you need to add it #test.test_type = #test_type. If you wanna save the change to database then update_attribute method is very useful for that purpose update_attribute(name, value), #test.update_attribute('test_type', #test_type)
Updated answer: Rails Guide says:
4.2.1 Methods Added by has_one
When you declare a has_one association, the declaring class automatically gains five methods related to the association:
association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {}
so try this #test.create_test_type(test_id: test.id), that bit of code can replace the following code I mentioned earlier #test.test_type (sorry I'm not Rails expert - still learning)

Related

Rails .includes() returning 'undefined method'

I have a Company object with an associated Location.
Company has_many :locations
Location belongs_to :company
When I call:
#company = Company.find(5).includes(:locations)
I get the error:
NoMethodError: undefined method `includes' for #<Company:0x000000066ad398>
I'm following the rubyonrails.org instructions to a T... as far as I can tell.
find() triggers a database query, and returns an instance of the model. You can't call includes on it, as includes is supposed to have an ActiveRecord::Relation as receiver.
You need to invert the order: find must stay at the end:
#company = Company.includes(:locations).find(5)
Did you check the records in the database on location.rb model. The company_id is there?
You can use pry-rails in order to debug the code. Your code looks ok.
The json you are creating is with jbuilder? because is that the case, you need to create the corresponding each loop.

Mongoid: finding documents that are referencing another one (referenced 1-N)

I have a MongoDB database that uses mongoid referencing according to the documentation. Here are my models:
class Mydoc
include Mongoid::Document
# ...
has_and_belongs_to_many :editors, class_name: 'User', inverse_of: nil
# ...
end
and
class User
# actually, it's based on devise with some changes
# ...
# it does not reference back to Mydoc, see inverse_of there!
end
Now if I make a reference to a user (to grant her/him editor role), mongoid creates an array field called editor_ids that contains object ids of the documents in the users table. Works nice.
I'd like to have a query that shows all Mydoc documents where a certain user is editor. Can't figure out how to do that in mongoid. It's very simple in the mongo console:
db.mydocs.find({ editor_ids: { $in: [ ObjectId("52c97e58b878bcf156000001") ] } })
It works like charm. But I need this in rails, not in the console. Based on mongoid docs, I've tried this (and a hell lot of variations of it) but it does not work:
#docs_where_editor = Mydoc.where(:editors.in => [#user._id])
the result is an empty dataset. I would appreciate any hint.
I suppose it's not the where method, since in mongoid, find only accepts object ids you want to find.
If you have an :editor_ids array and you're only looking for a single value then you should be able to use multi-keys thusly:
Mydoc.where(:editor_ids => #user.id)
and if you have several editor IDs to search for then:
Mydoc.where(:editors_ids.in => array_of_user_ids)
would be the transliteration of your MongoDB console query to Mongoid.

Correct way to create or update with multiple belongs_to in Rails

New to Rails and Ruby and trying to do things correctly.
Here are my models. Everything works fine, but I want to do things the "right" way so to speak.
I have an import process that takes a CSV and tries to either create a new record or update an existing one.
So the process is 1.) parse csv row 2.) find or create record 3.) save record
I have this working perfectly, but the code seems like it could be improved. If ParcelType wasn't involved it would be fine, since I'm creating/retrieving a parcel FROM the Manufacturer, that foreign key is pre-populated for me. But the ParcelType isn't. Anyway to have both Type and Manufacturer pre-populated since I'm using them both in the search?
CSV row can have multiple manufacturers per row (results in 2 almost identical rows, just with diff mfr_id) so that's what the .each is about
manufacturer_id.split(";").each do |mfr_string|
mfr = Manufacturer.find_by_name(mfr_string)
# If it's a mfr we don't care about, don't put it in the db
next if mfr.nil?
# Unique parcel is defined by it's manufacturer, it's type, it's model number, and it's reference_number
parcel = mfr.parcels.of_type('FR').find_or_initialize_by_model_number_and_reference_number(attributes[:model_number], attributes[:reference_number])
parcel.assign_attributes(attributes)
# this line in particular is a bummer. if it finds a parcel and I'm updating, this line is superfulous, only necessary when it's a new parcel
parcel.parcel_type = ParcelType.find_by_code('FR')
parcel.save!
end
class Parcel < ActiveRecord::Base
belongs_to :parcel_type
belongs_to :manufacturer
def self.of_type(type)
joins(:parcel_type).where(:parcel_types => {:code => type.upcase}).readonly(false) unless type.nil?
end
end
class Manufacturer < ActiveRecord::Base
has_many :parcels
end
class ParcelType < ActiveRecord::Base
has_many :parcels
end
It sounds like the new_record? method is what you're looking for.
new_record?() public
Returns true if this object hasn’t been saved yet — that is, a record
for the object doesn’t exist yet; otherwise, returns false.
The following will only execute if the parcel object is indeed a new record:
parcel.parcel_type = ParcelType.find_by_code('FR') if parcel.new_record?
What about 'find_or_create'?
I have wanted to use this from a long time, check these links.
Usage:
http://rubyquicktips.com/post/344181578/find-or-create-an-object-in-one-command
Several attributes:
Rails find_or_create by more than one attribute?
Extra:
How can I pass multiple attributes to find_or_create_by in Rails 3?

Assigning rails association using strings

Say I have two models and one belongs to another. Now normaly you would assign an object to the association when populating the fields. Does rails allow overriding the set method so that the association assignment can be customised?
E.g
class Person
# something about shirts
end
class Shirt
belongs_to :person
def person=(p)
self.person = Person.find_or_create_by_name(p)
end
end
And then use something like so auto bind the association but using a string to do the searching and binding automatically. Is this possible?
s = Shirt.new
s.person = "Test Person"
Thanks
ROR Guides cover the association extension you need.
UPDATE:
Actually, overriding setter is not that bad, once you understand what you're doing. But you have to be careful, since it can cause infinite loop (as in your example). So if you're using Rails 3.2, you have to use super, in other case you have to use alias_method_chain.

how to force a has_many to use a specific :foreign_key?

I'm having trouble with a model not honoring the :foreign_key policy.
Character model has the following fields:
name:string
level:int
realm:string
realm_id:integer
class Character < ActiveRecord::Base
belongs_to :realm
end
My Realms model looks like this:
class Realm < ActiveRecord::Base
has_many :characters, :foreign_key => "realm_id"
end
However, it seems like it's forcing the character model to use the :realm column as the foreign_key rather than :realm_id. I don't have any clue as to why or how to fix it. Is there any other way to make it ignore the :realm field and go for the :realm_id without having to change the name of the column?
[Edit for clarity]
The character model does have a realm_id:integer field. I have tried not having the foreign_key but the results with both is identical.
ruby-1.9.2-p136 :012 > c = Character.new
=> #
ruby-1.9.2-p136 :013 > c.realm = "Sargeras"
ActiveRecord::AssociationTypeMismatch: Realm(#2154038240) expected, got String(#2151988680)
Despite even having the foreign_key, it just refuses to let go of the realm column.
[Edit 2]
The realm column will just take over due to the has_many and belongs_to association. There is no way so far to break this, so the solution is to either remove the column (the approach i will take), or rename it to something different.
Did you make sure that your Character table has a realm_id column? Please make sure of that, and then get rid of foreign_key => 'realm_id, it is not necessary at all. Your program should work if you get both these things done.
You should not need the :foreign_key part here at all, since you're following the standard Rails naming convention, the realm_id column should be inferred from the model name.
EDIT
I see. I don't think you can have a column and an association by the same name in one model. The easiest solution would probably be to rename the "realm" column to "realmname" or something like that.
belongs_to :realm creates (among other things) methods called realm and realm= used as getters and setters. That means the method_missing magic that ActiveRecord uses to expose database columns as attributes is never triggered when you do Character#realm, as that method isn't in fact missing.
If you want to avoid renaming the realm column in your database, you could create attribute accessors for the field manually under another name:
class Character < ActiveRecord::Base
def realm_name
self['realm']
end
def realm_name=(value)
self['realm'] = value
end
end
This way you'll still have the realm column in your database and be able to access the attribute in Ruby, albeit under a different name. This isn't a great idea, though, as you'll be duplicating the realm name as both Character#realm_name and Character.realm.name.
I would ditch the realm column and instead make sure I use Realm objects when importing from the datasource:
character.realm = Realm.find_by_name('Sargeras')
That way you'd only realm data available where it makes sense; in the Realm model.

Resources