'How should I set these associations up properly?
I am trying to build a blog-style app. I have 3 models - Users, Projects and Posts.
Users have_many projects, users have_many posts.
Projects belong_to users, projects have_many posts
Posts belong_to Users, posts belong_to projects
I have tried setting up the project a number of different ways, following a range of published solutions and I keep hitting many errors. The latest and greatest error
At the moment I am hitting a ActiveRecord::InvalidForeignKey in PostsController#create SQLite3::ConstraintException: FOREIGN KEY constraint failed error.
Solution 1:[1]
rails generate model Project title:string user:references this command will make the project belong to a user and the user model add has_many projects
the same thing applies for posts
Solution 2:[2]
Assuming you have the User model and table already generated then generate scaffold
rails g scaffold Post user:references
rails will create a migration that adds a column named user_id to the Post table and creates an index on it. For both tables. Rails will also add belongs_to :user in the Post model.
You can add a has_many to a model as long as another model belongs_to the first model and has a migration with the foreign key column. The same should be done to the Project Model as the association between projects and posts use the same concept of users and posts
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shaher Shamroukh |
| Solution 2 | Shaher Shamroukh |
