D
D
Denis Zakorov2015-03-27 22:33:10
Ruby on Rails
Denis Zakorov, 2015-03-27 22:33:10

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)

routes.rb
get ':project_url/:category_url', to: 'pr#category'

Category Creation Method
def create
  @category = @project.categories.build(category_params)
  if @category.save
    redirect_to ...
  end
end

Additional Resources
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

1 answer(s)
T
thepry, 2015-03-27
@thepry

How to display projects assigned to a specific category?

If you can have several projects in one category, then this is a one-to-many relationship.
1. Вам нужно добавить has_one :project, или has_many :projects в класс Category.
2. Код будет @category.projects

In general, you do not have a very correct connection. According to the code, the category is subordinate to the project - it is created after and in the url is after the project, so it would be more correct for the category to be belongs_to.
Well, decide whether you have a project / projects inside the category, or there is a category / categories inside the project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question