Rails ActiveRecord updating fields - ruby-on-rails

My Example:
class Category < ActiveRecord::Base
has_many :tags, :as => :tagable, :dependent => :destroy
def tag_string
str = ''
tags.each_with_index do |t, i|
str+= i > 0 ? ', ' : ''
str+= t.tag
end
str
end
def tag_string=(str)
tags.delete_all
Tag.parse_string(str).each { |t| tags.build(:tag => t.strip) }
end
end
How would you optimize this tag_string field? I don't want to delete all the tags every time I would like to just update them. Is there a better way to parse string with tags?
I do not want use a plugin! Thx.

I know you don't want to use a plugin, but you might want to dig through the source of acts_as_taggable_on_steroids to see how they're handling these situations. From my experience, working with that plugin has been very painless.

class Category < ActiveRecord::Base
has_many :tags, :as => :tagable, :dependent => :destroy
def tag_string
tags.map {|t| t.name }.join ', '
end
def tag_string=(str)
tags = Tag.parse_string(str)
end
end
I don't know what Tag.parse_string(str) method do. If it returns an array of Tag objects, than my example should work. And I'm not sure if this will only update, or delete old and add new one. You can test it and look in logs what it really does.

I agree with other commenters. You are better off using the plugin here. Here is one solution.
class Category < ActiveRecord::Base
has_many :tags, :as => :tagable, :dependent => :destroy
def tag_string
tags.collect(&:name).join(", ")
end
def tag_string=(str)
# Next line will delete the old association and create
# new(based on the passed str).
# If the Category is new, then save it after the call.
tags = Tag.create(str.split(",").collect{ |name| {:name => name.strip} })
end
end

Related

How to validate person_ids in Rails model?

In my Rails app, I have a has_many through relationship between two models and therefore I am creating new objects like this:
Project.new(:name => 'Test', :person_ids => [1, 2, 3])
What is a good way to validate those person_ids in the model?
This is what I have so far:
class Project < ActiveRecord::Base
has_many :people_projects
has_many :people, :through => :people_projects
validates :person_ids, inclusion => { :in => lambda { |x| x.valid_people } }
def valid_people
user.people.map(&:id)
end
end
However, this doesn't work because the person_ids get posted in an array.
Can anybody help?
Use a custom validation method like
class Project < ActiveRecord::Base
validate :valid_people
def valid_people
people = user.people.pluck(:id)
if person_ids.blank? || (person_ids - people).any?
errors.add(:person_ids, "Please add real people")
end
end
end

has_many autosave_associated_records_for_*

I am trying to associate existing records while still being able to add new ones. The following does not work but is pretty close to what I need. How can I accomplish associating existing records and creating new ones?
has_many :comments, :through => :commentings, :source => :commentable, :source_type => "Comment"
accepts_nested_attributes_for :comments, :allow_destroy => true
def autosave_associated_records_for_comments
comments.each do |comment|
if existing_comment = Comment.find_by_fax_and_name(comment.fax, comment.name)
self.comments.reject! { |hl| hl.fax == existing_comment.fax && hl.name == existing_comment.name }
self.comments << existing_comment
else
self.comments << comment
end
end
end
Here is a relevant line of source: https://github.com/rails/rails/blob/v3.0.11/activerecord/lib/active_record/autosave_association.rb#L155
I've made a solution, but if you know of a better way to do this please let me know!
def autosave_associated_records_for_comments
existing_comments = []
new_comments = []
comments.each do |comment|
if existing_comment = Comment.find_by_fax_and_name(comment.fax, comment.name)
existing_comments << existing_comment
else
new_comments << comment
end
end
self.comments << new_comments + existing_comments
end
I have a tagging system that utilizes a has_many :through relationship. Neither of the solutions here got me where I needed to go so I came up with a solution that may help others. This has been tested on Rails 3.2.
Setup
Here are a basic version of my Models:
Location Object:
class Location < ActiveRecord::Base
has_many :city_taggables, :as => :city_taggable, :dependent => :destroy
has_many :city_tags, :through => :city_taggables
accepts_nested_attributes_for :city_tags, :reject_if => :all_blank, allow_destroy: true
end
Tag Objects
class CityTaggable < ActiveRecord::Base
belongs_to :city_tag
belongs_to :city_taggable, :polymorphic => true
end
class CityTag < ActiveRecord::Base
has_many :city_taggables, :dependent => :destroy
has_many :ads, :through => :city_taggables
end
Solution
I did indeed override the autosave_associated_record_for method as follows:
class Location < ActiveRecord::Base
private
def autosave_associated_records_for_city_tags
tags =[]
#For Each Tag
city_tags.each do |tag|
#Destroy Tag if set to _destroy
if tag._destroy
#remove tag from object don't destroy the tag
self.city_tags.delete(tag)
next
end
#Check if the tag we are saving is new (no ID passed)
if tag.new_record?
#Find existing tag or use new tag if not found
tag = CityTag.find_by_label(tag.label) || StateTag.create(label: tag.label)
else
#If tag being saved has an ID then it exists we want to see if the label has changed
#We find the record and compare explicitly, this saves us when we are removing tags.
existing = CityTag.find_by_id(tag.id)
if existing
#Tag labels are different so we want to find or create a new tag (rather than updating the exiting tag label)
if tag.label != existing.label
self.city_tags.delete(tag)
tag = CityTag.find_by_label(tag.label) || CityTag.create(label: tag.label)
end
else
#Looks like we are removing the tag and need to delete it from this object
self.city_tags.delete(tag)
next
end
end
tags << tag
end
#Iterate through tags and add to my Location unless they are already associated.
tags.each do |tag|
unless tag.in? self.city_tags
self.city_tags << tag
end
end
end
The above implementation saves, deletes and changes tags the way I needed when using fields_for in a nested form. I'm open to feedback if there are ways to simplify. It is important to point out that I am explicitly changing tags when the label changes rather than updating the tag label.
In Rails 6 (and probably earlier versions too), it's easy to overwrite the attributes writer generated by accepts_nested_attributes_for and use find_or_initialize_by.
In this case, you could simply write:
has_many :comments, :through => :commentings, :source => :commentable, :source_type => "Comment"
accepts_nested_attributes_for :comments, :allow_destroy => true
def comments_attributes=(hashes)
hashes.each { |attributes| comments << Comment.find_or_initialize_by(attributes)
end
Haven't tested this when passing :id or :_destroy keys, as it doesn't apply in my situation, but feel free to share your thoughts or code if you do.
I would love to see Rails implement this natively, perhaps by passing an upsert: true option to accepts_nested_attributes_for.

Rails 3: Escape characters (\) appearing in part of JSON string

Anyone know why some of my json elements are being backslash(\) escaped while others are not?
{"first":"John","last":"Smith","dogs":"[{\"name\":\"Rex\",\"breed\":\"Lab\"},{\"name\":\"Spot\",\"breed\":\"Dalmation\"},{\"name\":\"Fido\",\"breed\":\"Terrier\"}]"}
Ideally I'd like NONE of them to be escaped...
This was generated by overriding as_json in two models. Person has_many Dogs.
#models/person.rb
class Person < ActiveRecord::Base
has_many :dogs
def as_json(options={})
{
:first => first,
:last => last,
:dogs => dogs.to_json
}
end
end
#models/dog.rb
class Dog < ActiveRecord::Base
belongs_to :people
def as_json(options={})
{
:name => name,
:breed => breed
}
end
end
Check out jonathanjulian.com's Rails to_json or as_json?
Try removing the to_json on dogs.to_json.

Model Relationship Problem

I am trying to calculate the average (mean) rating for all entries within a category based on the following model associations ...
class Entry < ActiveRecord::Base
acts_as_rateable
belongs_to :category
...
end
class Category < ActiveRecord::Base
has_many :entry
...
end
class Rating < ActiveRecord::Base
belongs_to :rateable, :polymorphic => true
...
end
The rating model is handled by the acts as rateable plugin, so the rateable model looks like this ...
module Rateable #:nodoc:
...
module ClassMethods
def acts_as_rateable
has_many :ratings, :as => :rateable, :dependent => :destroy
...
end
end
...
end
How can I perform the average calculation? Can this be accomplished through the rails model associations or do I have to resort to a SQL query?
The average method is probably what you're looking for. Here's how to use it in your situation:
#category.entries.average('ratings.rating', :joins => :ratings)
Could you use a named_scope or custom method on the model. Either way it would still require some SQL since, if I understand the question, your are calculating a value.
In a traditional database application this would be a view on the data tables.
So in this context you might do something like... (note not tested or sure it is 100% complete)
class Category
has_many :entry do
def avg_rating()
#entries = find :all
#entres.each do |en|
#value += en.rating
end
return #value / entries.count
end
end
Edit - Check out EmFi's revised answer.
I make no promises but try this
class Category
def average_rating
Rating.average :rating,
:conditions => [ "type = ? AND entries.category_id = ?", "Entry", id ],
:join => "JOIN entries ON rateable_id = entries.id"
end
end

Rails model with foreign_key and link table

I am trying to create a model for a ruby on rails project that builds relationships between different words. Think of it as a dictionary where the "Links" between two words shows that they can be used synonymously. My DB looks something like this:
Words
----
id
Links
-----
id
word1_id
word2_id
How do I create a relationship between two words, using the link-table. I've tried to create the model but was not sure how to get the link-table into play:
class Word < ActiveRecord::Base
has_many :synonyms, :class_name => 'Word', :foreign_key => 'word1_id'
end
In general, if your association has suffixes such as 1 and 2, it's not set up properly. Try this for the Word model:
class Word < ActiveRecord::Base
has_many :links, :dependent => :destroy
has_many :synonyms, :through => :links
end
Link model:
class Link < ActiveRecord::Base
belongs_to :word
belongs_to :synonym, :class_name => 'Word'
# Creates the complementary link automatically - this means all synonymous
# relationships are represented in #word.synonyms
def after_save_on_create
if find_complement.nil?
Link.new(:word => synonym, :synonym => word).save
end
end
# Deletes the complementary link automatically.
def after_destroy
if complement = find_complement
complement.destroy
end
end
protected
def find_complement
Link.find(:first, :conditions =>
["word_id = ? and synonym_id = ?", synonym.id, word.id])
end
end
Tables:
Words
----
id
Links
-----
id
word_id
synonym_id
Hmm, this is a tricky one. That is because synonyms can be from either the word1 id or the word2 id or both.
Anyway, when using a Model for the link table, you must use the :through option on the Models that use the Link Table
class Word < ActiveRecord::Base
has_many :links1, :class_name => 'Link', :foreign_key => 'word1_id'
has_many :synonyms1, :through => :links1, :source => :word
has_many :links2, :class_name => 'Link', :foreign_key => 'word2_id'
has_many :synonyms2, :through => :links2, :source => :word
end
That should do it, but now you must check two places to get all the synonyms. I would add a method that joined these, inside class Word.
def synonyms
return synonyms1 || synonyms2
end
||ing the results together will join the arrays and eliminate duplicates between them.
*This code is untested.
Word model:
class Word < ActiveRecord::Base
has_many :links, :dependent => :destroy
has_many :synonyms, :through => :links
def link_to(word)
synonyms << word
word.synonyms << self
end
end
Setting :dependent => :destroy on the has_many :links will remove all the links associated with that word before destroying the word record.
Link Model:
class Link < ActiveRecord::Base
belongs_to :word
belongs_to :synonym, :class_name => "Word"
end
Assuming you're using the latest Rails, you won't have to specify the foreign key for the belongs_to :synonym. If I recall correctly, this was introduced as a standard in Rails 2.
Word table:
name
Link table:
word_id
synonym_id
To link an existing word as a synonym to another word:
word = Word.find_by_name("feline")
word.link_to(Word.find_by_name("cat"))
To create a new word as a synonym to another word:
word = Word.find_by_name("canine")
word.link_to(Word.create(:name => "dog"))
I'd view it from a different angle; since all the words are synonymous, you shouldn't promote any one of them to be the "best". Try something like this:
class Concept < ActiveRecord::Base
has_many :words
end
class Word < ActiveRecord::Base
belongs_to :concept
validates_presence_of :text
validates_uniqueness_of :text, :scope => :concept_id
# A sophisticated association would be better than this.
def synonyms
concept.words - [self]
end
end
Now you can do
word = Word.find_by_text("epiphany")
word.synonyms
Trying to implement Sarah's solution I came across 2 issues:
Firstly, the solution doesn't work when wanting to assign synonyms by doing
word.synonyms << s1 or word.synonyms = [s1,s2]
Also deleting synonyms indirectly doesn't work properly. This is because Rails doesn't trigger the after_save_on_create and after_destroy callbacks when it automatically creates or deletes the Link records. At least not in Rails 2.3.5 where I tried it on.
This can be fixed by using :after_add and :after_remove callbacks in the Word model:
has_many :synonyms, :through => :links,
:after_add => :after_add_synonym,
:after_remove => :after_remove_synonym
Where the callbacks are Sarah's methods, slightly adjusted:
def after_add_synonym synonym
if find_synonym_complement(synonym).nil?
Link.new(:word => synonym, :synonym => self).save
end
end
def after_remove_synonym synonym
if complement = find_synonym_complement(synonym)
complement.destroy
end
end
protected
def find_synonym_complement synonym
Link.find(:first, :conditions => ["word_id = ? and synonym_id = ?", synonym.id, self.id])
end
The second issue of Sarah's solution is that synonyms that other words already have when linked together with a new word are not added to the new word and vice versa.
Here is a small modification that fixes this problem and ensures that all synonyms of a group are always linked to all other synonyms in that group:
def after_add_synonym synonym
for other_synonym in self.synonyms
synonym.synonyms << other_synonym if other_synonym != synonym and !synonym.synonyms.include?(other_synonym)
end
if find_synonym_complement(synonym).nil?
Link.new(:word => synonym, :synonym => self).save
end
end

Resources