0

New to rails. I'm creating a project with several database tables all in relation to each other. I would like to know how to add a foreign key reference to an instance after it has been created. Code below:

In schema:

    class Blog < ActiveRecord::Base
      has_many :posts
      has_many :owners
      has_many :users, through: :owners
    end

    class Owner < ActiveRecord::Base
      belongs_to :user
      belongs_to :blog
    end

    class User < ActiveRecord::Base
       has_many :messages
       has_many :posts
       has_many :owners
       has_many :blogs, through: :owners
    end

Models:

class User < ActiveRecord::Base
   has_many :messages
   has_many :posts
   has_many :owners
   has_many :blogs, through: :owners
end

class Owner < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :owners
  has_many :users, through: :owners
end

In rails console:

blog1 = Blog.first
user1 = User.first
blog1.users = user1
NoMethodError: undefined method `each' for #<User:0x0000000487e9f8>
0

3 Answers 3

1

If you're trying to make it so that user1 becomes the owner of the blog, you could try

blog1 = Blog.first 
user1 = User.first 
Owner.create(user: user1, blog: blog1)

or

Owner.create(user: User.first, blog:Blog.first)

Hope I answered your question!

Sign up to request clarification or add additional context in comments.

Comments

0

Since a Blog has many Users, .users will be a collection (Array or ActiveRecord_Relation).

Try: blog1.users << user1

<< (shovel operator) docs

Comments

0

When you are writing blog1.users, you are getting back an array, so doing = something wouldn't work. While you can just add to the array using << or say array.push(), it's not the best practice.

Instead, has_many (or has_one, etc), allows you to use build_ notation to create related objects. So you could do: blog1.users.build, which will create a new user referenced for the blog. Or if you want to persist it, you can call .users.create

There are many ways to go around it, but using ActiveRecord methods if available is a nice way to keep code readable and short.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.