Answer the question
In order to leave comments, you need to log in
How to correctly get data from two tables (models)?
There are two tables projects and categories. Implemented a one-to-one relationship (one project - one category for it).
When creating a category for a project, the category id is written to the project table.
How to display projects assigned to a specific category?
I had a problem that with url ../:project_url/:category_url in the parameters the following
{"project_url"=>"foo", "category_url"=>"bar"} because I use gem 'friendly_id'
Now I have this
@projects = Project.joins(:category).where('id' => 1)
get ':project_url/:category_url', to: 'pr#category'
def create
@category = @project.categories.build(category_params)
if @category.save
redirect_to ...
end
end
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :project_url
t.integer :category_id
t.text :content
end
end
end
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :category_url
t.string :title
end
end
end
class Project < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
end
Answer the question
In order to leave comments, you need to log in
How to display projects assigned to a specific category?
1. Вам нужно добавить has_one :project, или has_many :projects в класс Category.
2. Код будет @category.projects
belongs_to.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question