Rails – check if record exists in has_many association
Try: current_user.items.exists?(params[:id]) Or current_user.items.exists?(@item.id)
Try: current_user.items.exists?(params[:id]) Or current_user.items.exists?(@item.id)
In this case you can modify ON condition with andOnCondition method: public function getImages() { return $this->hasMany(RecipeImage::className(), [‘imageable_id’ => ‘id’]) ->andOnCondition([‘imageable_type’ => ‘Person’]); } Official docs: andOnCondition:
Yes, I think you’ve just found a slightly odd-looking scenario in Rails. I suppose it might be useful to view “status” as a sort of category to which the bug belongs — in that light, it makes sense.
I would recommend checking out a gem called Shoulda. It has a lot of macros for testing things like relationships and validations. If all you want is to test that the has_many relationship exists, then you could do the following: describe Post do it { should have_many(:categories) } end Or if you’re testing a has_many … Read more
This is a self-referential model, you can try something like this: class Event < ActiveRecord::Base belongs_to :parent, :class_name => “Event”, :foreign_key => “parent_event_id” has_many :child_events, :class_name => “Event”, :foreign_key => “child_event_id” end That way, you can call @event.parent to get an ActiveRecord Event object and @event.child_events to get an ActiveRecord collection of Event objects
Simpler solution that’s built into Rails: class Blog < ActiveRecord::Base has_many :blogs_readers, :dependent => :destroy has_many :readers, :through => :blogs_readers, :uniq => true end class Reader < ActiveRecord::Base has_many :blogs_readers, :dependent => :destroy has_many :blogs, :through => :blogs_readers, :uniq => true end class BlogsReaders < ActiveRecord::Base belongs_to :blog belongs_to :reader end Note adding the :uniq … Read more
Unfortunately there are no such thing like associations_to_save. However there are some rules saying what is being saved when. You can find those here: http://guides.rubyonrails.org/association_basics.html. Points: 4.1.5 (belongs_to), 4.2.5 (has_one), 4.3.4 (has_many) and 4.4.4 (habtm). UPDATE: In case of has_many association, the child is saved on saving the parent if child.new_record? returns true (child was … Read more
Found a simple answer on IRC that seems to work (thanks to Radar): class Person < ActiveRecord::Base belongs_to :father, :class_name => ‘Person’ belongs_to :mother, :class_name => ‘Person’ has_many :children_of_father, :class_name => ‘Person’, :foreign_key => ‘father_id’ has_many :children_of_mother, :class_name => ‘Person’, :foreign_key => ‘mother_id’ def children children_of_mother + children_of_father end end
When using ApplicationSerializer which extends LSSerializer, it seems to work. Maybe it got fixed since asked?
A better solution has been provided by @SooDesuNe on this SO post validates :tags, length: { minimum: 1, maximum: 6 }