Rails belongs_to association is not working - ruby-on-rails-3

Here is my Course model
class Course < ActiveRecord::Base
attr_accessible :longdescription, :shortdescription, :title, :published_at
has_many :lessons, :foreign_key => 'course_id'
end
And Here is my Lesson model
class Lesson < ActiveRecord::Base
belongs_to :course, :class_name => 'Course'
attr_accessor :course_id
attr_accessible :description, :title, :course_id
end
I creates a lesson that belongs to a course. lesson created successfully
Lesson.create(:title => "testing", :description => "causing problems", :course_id => 1)
But when i fetch a record of lesson I got course_id=nil. Any Help???
<Lesson id: 8, title: "testing", description: "causing problems", course_id: nil, created_at: "2013-03-15 12:56:36", updated_at: "2013-03-15 12:56:36">

you need to remove the attr_accessor :course_id line in your model. If you have this line, it creates the following methods in your model which conflicts with what is defined by default
def course_id
#course_id
end
def course_id=(cid)
#course_id = cid
end

Remove attr_accessor :course_id in your Lesson model. This will override the default behavior of the activerecord.

Related

Rails simplify a query to get user profile's first_name

I want to retrieve application.applicant.profile.first_name for the applicant and I'm not able to retrieve the profile attribute:first_name using applicant above.
Profile, application are connected by foreign key: user_id to user.Can someone suggest a way?
Here are my associations:
user.rb
class User < ApplicationRecord
has_many :applications
has_one :profile, -> { where role: 'user' }, dependent: :destroy
profile.rb
class Profile < ApplicationRecord
belongs_to :user, :class_name => 'User', :foreign_key => 'user_id'
job.rb
class Job < ApplicationRecord
has_many :applications, :dependent => :destroy
has_many :applicants, :through => :applications, :class_name => 'User'
application.rb
class Application < ApplicationRecord
belongs_to :job
belongs_to :applicant, :class_name => 'User', :foreign_key => 'user_id'
This line isn't correct...
has_one :profile, -> { where role: 'user' }, class_name: 'User', dependent: :destroy
It should be...
has_one :profile, -> { where role: 'user' }, dependent: :destroy
The class_name for :profile is Profile but you don't need to specify it as it can be derived from the symbol by rails.
After numerous permutations and combinations such as polymorphic, select & join statement or even by providing a SQL query, finally realised that it was as simple as a single statement as I knew the user_id of current user:
<% post.applications.each do |papplication| %>
<%= Profile.find_by_user_id(papplication.user_id).first_name %> <% end %>

DB with multiple foreign keys linked to same Model on differents attributes

I am having difficulties building my DB relation, if anyone could give me a little help i would greatly appreciate!
I have one table named Person and another one called Company and Company has many Persons and Person belongs_to Company
Here the trick Company has_many Person threw an attribute called person and has_many Person threw another attribute called administrator
Could be see like
Coca-cola = Company.new
jonathan = Person.new / nicolas = Person.new
Coca-cola : {
person: jonathan,nicolas
administrator: nicolas
}
I did that first migration :
def change
add_reference :persons, :person, index: true
add_reference :persons, :administrator, index: true
add_foreign_key :persons, :companys, column: :person_id
add_foreign_key :persons, :companys, column: :administrator_id
end
then I added this relation to my model
class Company < ApplicationRecord
has_many :persons,
:class_name => "Person",
:foreign_key => "person_id"
has_many :administrators,
:class_name => "Person",
:foreign_key => "administrator_id"
end
and
class Person < ApplicationRecord
belongs_to :person,
:class_name => "Company",
optional: true
belongs_to :administrator,
:class_name => "Company",
optional: true
end
And unfortunately that doesnt working, any lead on what could cause the problem ?
Thanks a lots.
Jonathan.
Let me know if I understood your problem. Requirements are:
Person belongs_to Company
Company has_many Persons
Company has_many Administrators
I guess you could solve with the following code:
class ChangePersons < ActiveRecord::Migration
def change
add_column :persons, :administrator, :boolean, default: false
end
end
class Company < ApplicationRecord
has_many :persons, -> { where(administrator: false) }
has_many :administrators,
class_name: "Person",
foreign_key: "person_id",
-> { where(administrator: true) }
end
class Person < ApplicationRecord
belongs_to :company
end

'with_indifferent_access' with a polymorphic association in Rails 3

I'm trying to create a record with some nested attributes and the nested attributes are in a polymorphic model; something like this:
class Office < ActiveRecord::Base
attr_accessible :name, :description, :address_attributes
has_one :address, as: :location_data_source
accepts_nested_attributes_for :address
end
class Shop < ActiveRecord::Base
attr_accessible :name, :description, :address_attributes
has_one :address, as: :location_data_source
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
attr_accessible :street, :city
belongs_to :location_data_source, polymorphic: true
end
And I'd like to create a record like this:
o = Office.create(:name = 'The Big Office', description = 'a really big office' :address_attributes => [:street => 'main street', :city => 'No Name City'])
But I get an 'with_indifferent_access' error:
NoMethodError: undefined method `with_indifferent_access' for...
I think I'm struggling becuase I don't really understand what the error means. Any ideas?

Rails updating model through association

I have the following two models:
class Process < ActiveRecord::Base
has_many :activities, inverse_of: :artifact, dependent: :destroy
attr_accessible :name, :activities_attributes
def update_status!
if self.activities.all? {|a| a.completed? }
self.status = 'completed'
elsif self.activities.any? {|a| a.completed? }
self.status = 'in_progress'
else
self.status = 'not_started'
end
save!
end
end
class Activity < ActiveRecord::Base
belongs_to :process, inverse_of: :activities
attr_accessible :name,:completed_date
scope :completed, where("completed_date is not null")
end
Then in my Controller:
#activity = Activity.find(params[:id])
#activity.completed_date = Time.now
#activity.process.update_status!
If I put a debugger directly after this line, and print out #activity.completed it returns true, however #artifact.status is still "not_started" (assume no other activities).
However, if I add the following line before the update:
#activity.process.activities[#activity.process.activities.index(#activity)] = #activity
The status is updated correctly.
Why doesn't the change to #activity propagate into process.activities? And how can I make it propagate?
I don't this inverse_of works with has_many through. See this article: ActiveRecord :inverse_of does not work on has_many :through on the join model on create
Here is the relevant blurb from the RailsGuides:
There are a few limitations to inverse_of support:
They do not work with :through associations. They do not work with
:polymorphic associations. They do not work with :as associations. For
belongs_to associations, has_many inverse associations are ignored.

Rails 3 - trying to create polymorphic has_one association in console

Here's my code:
Models:
class Article < ActiveRecord::Base
attr_accessible :title, :author, :content, :imageable_attributes
has_one :image, as: :imageable, dependent: :destroy
accepts_nested_attributes_for :image, allow_destroy: true
validates_presence_of :title, :content, :author
end
class Image < ActiveRecord::Base
mount_uploader :image, ImageUploader
attr_accessible :image, :caption, :imageable_id, :imageable_type, :article_ref
validates_presence_of :image
belongs_to :imageable, :polymorphic => true
end
Here's what I've tried in console:
article = Article.create!(title: "test", content: "test", author: "test", image_attributes: {image: "test.jpg", caption: "test caption"})
This creates an Article without errors, but if I call:
article.image
I get:
=> nil
If I type in console:
article = Article.new(title: "test", content: "test", author: "test")
article.build_image(image: "test.jpg")
I get:
=> Validation failed: Image image can't be blank
Any help greatly appreciated, I'm very confused!
I believe it's necessary to supply the attachment itself, rather than just the path. As an example,
i = Image.new(
:image => File.join(Rails.root, "test.jpg")
)
i.image
# =>
but
i = Image.new(
:image => File.open(File.join(Rails.root, "test.jpg"))
)
i.image
# => /uploads/tmp/20120427-2155-1316-5181/test.jpg
It's not necessary to use File.open when saving using Multipart POST, though.