-1
與回報率我真的初學者,並試圖處理我的多對多協會Ruby on Rails的協會與模型許多一對多
我處理我的模型之間遷移
旅行模式
的關係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
我不`噸知道如何旅行分配給用戶,並在那裏寫在控制器或形式分配?
@ user.trips < < @trip不起作用