多対多の関係を持つ3つのテーブルからdevelopment.sqlite3
のデータを取得することができません。私は与えられた場所やカテゴリに属するコースを手に入れることができますが、それは周囲の道には向いていません。Rails 5.0.2 - 多対多のリレーションシップモデルからデータを取得できません
私はクラスで教えられた方法に従っていましたが、モデルにはいくつかの制約がありませんでした。
誰かが一度見て、私にいくつかの提案をしてください。どうもありがとうございます!
これは私のschema.rb
:
create_table "categories", force: :cascade do |t|
t.string "title"
end
create_table "categories_courses", force: :cascade do |t|
t.integer "course_id", null: false
t.integer "category_id", null: false
end
create_table "courses", force: :cascade do |t|
t.string "title"
end
create_table "courses_locations", force: :cascade do |t|
t.integer "course_id", null: false
t.integer "location_id", null: false
end
create_table "locations", force: :cascade do |t|
t.string "address"
end
私は場所や特定のコースに関連付けるカテゴリを取得したいです。それから私は、以下のようなmodels
内の関係を追加しました:
# Category model
class Category < ApplicationRecord
has_and_belongs_to_many :courses, join_table: 'categories_courses'
end
# Location model
class Location < ApplicationRecord
has_and_belongs_to_many :courses, join_table: 'courses_locations'
end
# Course model
class Course < ApplicationRecord
has_and_belongs_to_many :locations, join_table: 'courses_locations'
has_and_belongs_to_many :categories, join_table: 'categories_courses'
end
はその後courses_controller.rb
に、私はこのような場所やカテゴリを取得:
class CoursesController < ApplicationController
before_action :set_course, only: [:show, :edit, :update, :destroy]
def categories
@course = Course.find params[:id]
@categories = @course.categories
end
def locations
@course = Course.find params[:id]
@locations = @course.locations
end
private
def set_course
@course = Course.find(params[:id])
end
end
は、最後に私はこのようなhtml.erb
ファイル内のデータを表示します
<% course.categories.each {|category| puts category.title + ' '} %>
<% course.locations.each {|location| puts location.address + ' '} %>
ここにコードをたくさん残して申し訳ありませんが、コードを調べるのに十分な情報を提供する必要があります。
更新:
私はroute.rb
Rails.application.routes.draw do
resources :locations
resources :categories
resources :courses
end
でこれを持って、私はすべての人の提案として、コードを編集しているが、それはまだ何も出力しません。私は、クエリが正しいことに気づくが、rails s
コンソールに警告があります:
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 35], ["LIMIT", 1]]
DEPRECATION WARNING: Passing an argument to force an association to reload is now deprecated and will be removed in Rails 5.1. Please call `reload` on the result collection proxy instead. (called from block in _app_views_courses_index_html_erb___1034719630_104325280 at c:/Users/lovea/RubymineProjects/YourCourse/app/views/courses/index.html.erb:41)
Category Load (0.0ms) SELECT "categories".* FROM "categories" INNER JOIN "categories_courses" ON "categories"."id" = "categories_courses"."category_id" WHERE "categories_courses"."course_id" = ? [["course_id", 4]]
collecionのチェックボックスで、多くの多くのビューを作成することができますか?あなたはカテゴリ/場所を与えられたコースに入れることができませんか?これはRailsのバージョンは何ですか? 'course.categories(course.id)'これは何をすると思われますか?それはちょうど '@ course.categories'でしょうか? – Fallenhero