1

I've created a simple webapp with user authentication. I've made two models: Users for user authentication and Details for additional user details. They are associated with one-to-one relationship. I'm having problems with updating two models from the same controller.

Is one-to-one association recommended at all in this case (I'm not willing to shove too many fields in one table), and if so, what is the proper way of handling two models via one controller?

aL3xa
  • 35,415
  • 18
  • 79
  • 112

2 Answers2

3

Check Nested Model Form Part 1/2 by rails cast. Checkout the rails cast and you can surely figure out :) Its explained for many to many relationships, minor tweeks and you can do it for one to one.

Some sample code you may want to see:

class Wiki < ActiveRecord::Base
  has_many :revisions 

  has_one :latest_revision, :class_name => "Revision", :order => 'updated_at desc', :limit => 1
  accepts_nested_attributes_for :revisions
end

class Revision < ActiveRecord::Base
  belongs_to :wiki
end


# new Wiki page, first revision
def new
  @wiki = Wiki.new
  @revision = @wiki.revisions.build
end

def create
  @wiki=Wiki.new(params[:wiki])
  @wiki.save
end

# adding a Revision to a Wiki page
def edit
  @wiki = Wiki.find(params[:id])
  @revision = @wiki.revisions.build # creating a new revision on edit
end

def update
  @wiki=Wiki.new(params[:wiki])
  @wiki.save
end

def show
  @wiki = Wiki.find(params[:id])
  @revision = @wiki.latest_revision
end
Mohit Jain
  • 43,139
  • 57
  • 169
  • 274
  • I forgot to add that I've seen both parts of RailsCasts, and I dunno if it should fit my situation here. But thanks! (I always search RailsCasts before I ask =D ) – aL3xa Mar 19 '12 at 23:28
-1

Yes use of one to one us justified, as you said for keeping things compartmentalized. As of accessing them from controller you should be able to do it as long as you have defined the associations properly in the models.

the User model must have:

has_one : detail

and the Detail model must have:

belongs_to : user

then if you have a foreign key called 'user_id' in the 'details' table, everything should work fine.

now you can access both models using each other like

User.find(1).detail

or

Detail.find(1).user

you can now update both in the same way from both their controllers.

Shaunak
  • 17,377
  • 5
  • 53
  • 84