jjabrams jjabrams - 7 months ago 22
Ruby Question

Rails find_by_name on another table

I have Genders and based on Gender name create category and subcategories.

m = Gender.create(:gender => 'masculine')

c = Category.find_by_name("T-shirt", gender: m )
c.subcategories.create(:name => "Necklace" )


and so on.

Answer

You can try this.

m = Gender.create(:gender => 'masculine')

c = Category.where(name: "T-shirt", gender: m.gender ).first

c.subcategories.create(name: "Necklace" )

Please note above code will raise an exception if no category found with given condition, so to avoid that you can use following.

m = Gender.create(:gender => 'masculine')

c = Category.where(name: "T-shirt", gender: m.gender).try(:first)

unless c.blank?
  c.subcategories.create(name: "Necklace" )
end
Comments