user1202888
user1202888

Reputation: 1043

Using class variable

Beginner here, learning ruby on rails by jumping into a project. This question is probably pure ruby and has nothing to do with rails. I also want to note that I'm using Active_Admin.

I have the following 2 classes: Owner and Phone.

class Owner < ActiveRecord::Base
  attr_accessible :email, :password,
  has_many :phones
end

class Phone < ActiveRecord::Base
  attr_accessible :owner_id :model
  belongs_to :owner
end

How would I go accessing the owners email from within the phones model, for example:

form do |f|
  f.inputs "Phone Details" do
    f.input :model
    f.input :owner_id   # This is where I want the email, not the owners id.
  end
  f.buttons
end

It looks like I should review the pickaxe book and refine my ruby before jumping into rails.

Thanks

Upvotes: 0

Views: 76

Answers (2)

Pavel
Pavel

Reputation: 4410

In this case you should use nested form. Usage of nested form is explained very well in this railscast.

Upvotes: 0

Ben
Ben

Reputation: 13625

to have both the owner and the phone in one form, your form should look something like this:

form_for @phone do |phone_form|
  phone_form.label :model
  phone_form.text_field :model
  fields_for @phone.owner do |owner_fields|
    owner_fields.label :email
    owner_fields.text_field :email

If you use this method, make sure you can update the Owner from the Phone model by setting accepts_nested_attributes_for :owner on you Phone model.

Upvotes: 1

Related Questions