我找不到关联的问题,但不断收到与关联相关的错误。我将has_many添加到学校,并将belongs_to添加到成员。
class CreateSchools < ActiveRecord::Migration[5.0]
def change
create_table :schools do |t|
t.string :name
t.timestamps
end
端
class AddSchoolRefToMembers < ActiveRecord::Migration[5.0]
def change
add_reference :members, :school, foreign_key: true
end
端 端
class MembersController < ActionController::Base
before_action :set_school
def index
@members = Member.all
end
def new
@member = Member.new
end
def create
@member = Member.new(member_params)
@member.school = @school
@member.save
redirect_to members_path
end
private
def set_school
@school = School.find(params[:school])
end
def member_params
params.require(:member).permit(:name, :email,:school)
end
端
控制器:
{{1}}
端
答案 0 :(得分:0)
不应分配@school本身,而应分配该学校的ID:
def create
@member = Member.new(member_params)
@member.school = @school.id # here it is @school.id
@member.save
redirect_to members_path
end
关联使用ID而不是Arrays。 @school完全返回学校记录,你只需要id来创建关联。