dsignr
dsignr

Reputation: 2354

Rails doesn't respect model associations for has_one

User.rb

has_one :subscription, :inverse_of => :user

Subscription.rb

has_one :credit_card, :inverse_of => :subscription

CreditCard.rb

belongs_to :user, :inverse_of => :credit_card
belongs_to :subscription, :inverse_of => :credit_card

In credit card controller:

def new
   @credit_card = current_user.build_credit_card
end

def create
   @credit_card = current_user.build_credit_card
end

if @credit_card.save
    if @credit_card.save
    format.html { redirect_to @credit_card, notice: 'Credit card was successfully created.' }
    format.json { render action: 'show', status: :created, location: @credit_card }
  else
    format.html { render action: 'new' }
    format.json { render json: @credit_card.errors, status: :unprocessable_entity }
  end
end

However, I'm still able to add multiple credit cards to my user model. How can this be possible? Only a has_many should emit such behaviour if I'm correct? A has_one association should prevent additional entities from being created, apart from one as far as I know..

I tried all variations, but still no luck.

Any help would be much appreciated!

Thank you.

Upvotes: 2

Views: 431

Answers (1)

Shaun Frost Duke Jackson
Shaun Frost Duke Jackson

Reputation: 1266

I've never used a has_one relationship but the power of google and stack overflow has helped me understand this.

Difference between has_one and belongs_to in Rails?

belongs_to means that the foreign key is in the table for this class. So belongs_to can ONLY go in the class that holds the foreign key.

has_one

means that there is a foreign key in another table that references this class. So has_one can ONLY go in a class that is referenced by a column in another table.

Also a nice way to remember it in that post:

I always think of it in terms of Toy Story. Andy 'has_one' Woody, Woody 'belongs_to' andy. Where is the foreign key? On Woody's sole.

Also this is useful for understanding relationships.

http://requiremind.com/differences-between-has-one-and-belongs-to-in-ruby-on-rails/

Upvotes: 2

Related Questions