How to search in rails from two models?

I have two models, Listing and Profile, configured with Active Admin. I want to create a system in which for each new listing, a profile is automatically created and linked. How should I approach this?

  • The model Profile is generated using Devise. I have established a has one relationship between them. Note: Imagine the two models like airbnb in which a seller can have only one listing and cannot rent Side note: My model Profile is not registerable. So using it through activeadmin is important so that once listing and profile are created by the superuser, I can send the login details to the person and they can login to view their listing. PS: Rails Newbie Here! So easier methods,tutorials or directions will be truly appreciated and if you are in or near London thanked by a beer.

  • Answer:

    If you just want to create a Profile you can use a before_validate ActiveRecord callback to check if a Profile exists. If not you simply build one: class Listing < ActiveRecord::Base has_one :profile accepts_nested_attributes_for :profile before_validation :build_profile_if_missing private def build_profile_if_missing self.profile ||= build_profile(profile_attributes) end end class Profile < ActiveRecord::Base belongs_to :listing end Something along those lines.

Marcel Scherf at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.