我是RoR的初学者并试图处理我的许多协会
我处理了我的模型与迁移之间的关系
旅行模式
class Trip < ActiveRecord::Base
has_many :relationships
has_many :topics, through: :relationships
end
用户模型
class User < ActiveRecord::Base
has_many :relationships
has_many :trips, through: :relationships
end
关系模型
class Relationship < ActiveRecord::Base
belongs_to :user
belongs_to :trip
end
我的迁移
class CreateRelationships < ActiveRecord::Migration
def change
create_table :relationships do |t|
t.belongs_to :user
t.belongs_to :trip
t.timestamps
end
add_index :relationships, :user_id
add_index :relationships, :trip_id
end
end
User_controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def trips
@user = User.find(params[:id])
@trips = @user.trips
end
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
@trips = Trip.all
end
def edit
end
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name)
end
end
我不知道如何分配Trip to User以及在控制器或表单中写入赋值的位置??
@ user.trips&lt;&lt; @trip不工作
答案 0 :(得分:0)
在模态中更改为: -
旅行模式
class Trip < ActiveRecord::Base
has_many :relationships
has_many :users, through: :relationships
end
用户模型
class User < ActiveRecord::Base
has_many :relationships
has_many :trips, through: :relationships
end
然后尝试: -
@user.trips << @trip