and diffs just the new stuff. @post = Post.find(params[:id]) new_tags = params[:tags].split(",").map(&:strip).map do |tag_name| Tag.find_or_initialize_by(name: tag_name) end @post.tags.replace(new_tags) @post.tags.replace(["doo", "ggie", "gaga"]) # => ActiveRecord::AssociationTypeMismatch: Tag expected, got String
Works great with scope class Post < ApplicationRecord scope :featured, -> { where(featured: true) } scope :recent, -> { where("created_at > ?", 2.days.ago) } end Post.featured.or(Post.recent) # SELECT "posts".* FROM "posts" # WHERE ("posts"."featured" = ? # OR (created_at > '2016-08-08 17:07:58.750856')) [["featured", true]]
a bit easier def self.[](name) self.arel_table[name] end end Post.where(Post[:created_at].gt 2.days.ago) # Same as : Post.where(Post.arel_table[:created_at].gt 2.days.ago) # Same as: Post.where('created_at > ?', 2.days.ago) # SELECT "posts".* FROM "posts" WHERE ("posts"."created_at" > '2016-08-08 17:38:46.068891')