I have a model called Course which needs to be associated with exams and assignments. I want to able to write code like this:
>>c = Course.new
>>assignment1 = c.assignments << Assignment.new
>>exam1 = c.exams << Exam.new
c.assessments should now include both exam1 and assignment1
How I think this should be accomplished (using single table inheritance from the Assessment model):
class Course < ActiveRecord::Base
has_many :assessments
attr_accessible :title, :name, :startDate, :endDate, :color
end
class Assessment < ActiveRecord::Base
belongs_to :course
attr_accessible :end_at, :name, :start_at, :type, :weight
end
class Assignment < Assessment
end
class Exam < Assessment
end
I've tried my best to find out how to do this but i cant seem to figure it out. Any help would be appreciated.
Course has only assesments associations so you should be able to write code like this:
c = Course.new
c.assesments << Assignment.new
c.assesments << Exam.new
Also make sure that assesments table has type column with datatype string.
Related
I want to know what I'm doing wrong as my Categories "name" that I specify on rails console are not uploading directly to my postgresql database.
My first Model (category.rb)file
class Category < ApplicationRecord
attr_accessible :name
has_many :content
end
My Second Model (content.rb)file
class Content < ApplicationRecord
attr_accessible :title, :body, :category_id, :author_id
belongs_to :category
end
I've added two categories inside this model
"Football" and Cricket using the code below:
category = Category.create(:name => "Football")
category = Category.create(:name => "Cricket")
The above code creates category id and tables in the postgresql not the name I specified.
Please help.. Please reply if you need anything else
class Category < ApplicationRecord
attr_accessible :name
# has_many :content -- This is wrong
has_many :contents # This is how it should be
end
Also has hashrocket suggested try running migration.
What is the result of running the following in console?
c = Category.new
c.name = "football"
c.save
If this gives you an error then going through the error message will show what is wrong.
Consider a relationship like this:
class BuyableComponent < ActiveRecord::Base
attr_accessible :cost
end
class CartItem < ActiveRecord::Base
attr_accessible :quantity
belongs_to :buyable_component
def total_cost
# This should be buyable_component.cost, but how do I make an alias so
# I can just use 'cost'?
cost * quantity
end
end
I have a buyable_components table and a cart_items table. Like the comment describes, I would like to be able to use cart_item.cost instead of cart_item.buyable_component.cost. alias_attribute seems to be close to what I need, but not quite.
I'm looking for a way to declare this for all attributes of BuyableComponent.
try something like:
class CartItem < ActiveRecord::Base
delegate :cost, :to => :buyable_component
end
this should work I suppose
I'm using of Ruby on Rails.
I have some questions about definition of foreign key.
I defined some models.
When I access book title from class Trade via ISBN like this.
trade = Trade.first
trade.isbn #=> just get isbn in case 1.
trade.isbn.title #=> get book title in case 2.
Why case 2 doesn't work as expected??
class Trade < ActiveRecord::Base
attr_accessible :cost, :isbn, :shop_id, :volume
# belongs_to :book, foreign_key: "isbn" # case 1
belongs_to :isbn, class_name: :Book, foreign_key: :isbn # case 2
belongs_to :shop
end
class Author < ActiveRecord::Base
attr_accessible :age, :name
has_many :books
has_many :trades, through
end
class Book < ActiveRecord::Base
self.primary_key = :isbn
attr_accessible :author_id, :cost, :isbn, :publish_date, :title
belongs_to :author
end
class Shop < ActiveRecord::Base
attr_accessible :name
has_many :trades
end
I am not entirely sure what you're asking, what behavior you're seeing, or what behavior you expected. That said, this is what's happening with the code you've pasted (case 2?):
trade = Trade.first
trade.isbn
This returns the Book instance referenced by Trade#isbn.
trade.isbn.title
This is equivalent to
book = trade.isbn
book.title
which returns the title of the Book instance referenced by Trades#isbn. Is this not what you expected?
So Your question is what is difference between symbol (:isbn) and string ("isbn")?
In shot symbols are considered Rubys immutable strings You can read more here:
http://www.robertsosinski.com/2009/01/11/the-difference-between-ruby-symbols-and-strings/
In general convention is to use symbols as keys inside You options hashes that You pass to methods, though some libs/gems etc support both. But in particular case of Yours it looks like that this value is being typecasted to string, so everything that is passed as option to foreign_key will converted to string using to_s.
I am trying to order by a field in a related model in Rails. All of the solutions I have researched have not addressed if the related model is filtered by another parameter?
Item model
class Item < ActiveRecord::Base
has_many :priorities
Related Model:
class Priority < ActiveRecord::Base
belongs_to :item
validates :item_id, presence: true
validates :company_id, presence: true
validates :position, presence: true
end
I am retrieving Items using a where clause:
#items = Item.where('company_id = ? and approved = ?', #company.id, true).all
I need to order by the 'Position' column in the related table. The trouble has been that in the Priority model, an item could be listed for multiple companies. So the positions are dependent on which company_id they have. When I display the items, it is for one company, ordered by position within the company. What is the proper way to accomplish this? Any help is appreciated.
PS - I am aware of acts_as_list however found it did not quite suit my setup here, so I am manually handling saving the sorting while still using jquery ui sortable.
You could use the includes method to include the build association then order by it. You just make sure you disambiguate the field you are ordering on and there are some things you should read up on here on eager loading. So it could be something like:
#items = Item.includes(:priorities).where('company_id = ? and approved = ?', #company.id, true).order("priorities.position ASC")
class Item < ActiveRecord::Base
has_many :priorities
belongs_to :company
def self.approved
where(approved: true)
end
end
class Priority < ActiveRecord::Base
belongs_to :item
end
class Company < ActiveRecord::Base
has_many :items
end
#company = Company.find(params[:company_id])
#items = #company.items.joins(:priorities).approved.order(priorities: :position)
If I've understood your question, that's how I'd do it. It doesn't really need much explanation but lemme know if you're not sure.
If you wanted to push more of it into the model, if it's a common requirement, you could scope the order:
class Item < ActiveRecord::Base
has_many :priorities
belongs_to :company
def self.approved
where(approved: true)
end
def self.order_by_priority_position
joins(:priorities).order(priorities: :position)
end
end
and just use: #company.items.approved.order_by_priority_position
Hi I have two model Company and Feed
company.rb
class Company < ActiveRecord::Base
attr_accessible :rss_url, :name
has_many :feeds
end
feed.rb
class Feed < ActiveRecord::Base
attr_accessible :guid, :name, :published_at, :summary, :url
after_create { |feed| FeedEntry.update_from_feed(feed.feed_url) }
belongs_to :company
def self.update_from_feed(rss_url) ?????
feed = Feedzirra::Feed.fetch_and_parse(rss_url) ?????
add_entries(feed.entries)
end
end
How two take RSS_URL from company to feed ?
I don't know what add_entries does, but if you want to access the rss_url of Company inside Feed, you can use the association. Define this instance method on your Feed class.
def do_something
url = self.company.rss_url
puts "This feed belongs to a company with the following rss url: #{url}"
end