Answer the question
In order to leave comments, you need to log in
Ruby and Rail link two tables?
Hey, I'm making categories. But I just can not understand one chip.
Below is what I do.
As you can see, I have created a posts_category table for the categories.
And on the posts/new page,
I get an error about the absence of the categories table in the database.
Where does it come from? How to make him eat exactly posts_category?
class CreatePostsCategory < ActiveRecord::Migration
def change
create_table :posts_category do |t|
t.string :name
t.integer :user_id
t.timestamps
end
end
end
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.integer :user_id
t.string :title
t.text :description
t.belongs_to :category
t.timestamps
end
end
end
class Posts < ActiveRecord::Base
belongs_to :category
end
<%= f.collection_select :category_id, Category.order(:name), :id, :name %>
Answer the question
In order to leave comments, you need to log in
according to rails convention there can't be a label named posts_category
it can be post_categories - when one category has many posts, 1-to-many relationship and there can be categories and posts_categories tables - many-to-many relationship
That is, in your case, there should most likely be a post_categories label and belongs_to :post_category everywhere
Try replacing t.belongs_to :category with t.belongs_to :category, references: :posts_categories.
Naturally, you will have to specify the correct foreign_key and class_name in the models themselves, otherwise it will not work (despite the successful migration). Remember that Rails is Convention Over Configuration, deviating from conventions - be kind enough to specify a bunch of parameters (which you might not even know existed).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question