0

I have a Rails 4 app which has a Devise user. The Devise user can create multiple Apps and each App can contain multiple Certificates. At any given time tho and App can only have one production_certificate and one development_certificate. I believe that i setup the associations correctly here they are. My trouble now is how can i set the App to use one out of the many Certificates that an app owns to be the production/development certificate.

class App < ActiveRecord::Base
  belongs_to :user

  has_many :certificates

  belongs_to :production_certificate, class_name: 'Certificate'
  belongs_to :development_certificate, class_name: 'Certificate'
end

class Certificate < ActiveRecord::Base
  belongs_to :app
end
ny95
  • 680
  • 5
  • 17
  • Do you want to know how to use these associations to save the data correctly? – Bigxiang Aug 21 '13 at 03:49
  • Yeah, I don't understand what you want to do. If you just picked the first certificate to be the blessed certificate, that would work, but I doubt it is the answer you want. So, tell us why that is a bad answer. – Fred Aug 21 '13 at 05:20
  • @Bigxiang yes I'm trying to figure out how to save the data correctly. – ny95 Aug 21 '13 at 07:41
  • @Fred ^ I'm wondering how to save the data correctly – ny95 Aug 21 '13 at 07:42
  • So what results are you getting with your current code? (Your final sentence appears to ask for help selecting a certificate, which is why I asked) – Fred Aug 21 '13 at 13:12

1 Answers1

1

I'm trying to answer your question.

I suppose that you have an app object and some certificate objects.

At first, you get an App object.

app = App.find(YOUR ID)

app.certificates.each do |c|
  # In the loop, you can set your logic 
  # that selects which certificate is production certificate 
  # or development certificate

  if .....
    app.production_certificate = c

  elsif .....

    app.development_certificate = c
  end

end

app.save

I'm not sure the answer can solve your problem. If you have any question, please comment below.

Bigxiang
  • 6,252
  • 3
  • 22
  • 20
  • Thank you, this solved my problem and works perfectly. Is there anyway i can find out if a certificate if being used by an app programmatically from the certificate model? – ny95 Aug 21 '13 at 16:48
  • If a certificate is used by an app, then user_id of certificate must not be null. so you can use Certificate.where('user_id is not null') get all certificates is used. It returns an ActiveRecord::Relation, you can use it as an array. – Bigxiang Aug 22 '13 at 02:15