【问题标题】:Ruby on Rails Association with model many-to-manyRuby on Rails 与模型多对多关联
【发布时间】:2014-10-11 09:57:06
【问题描述】:

我是 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

用户控制器

 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 分配给 User 以及在控制器或表单中的何处写入分配??

@user.trips

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-4


    【解决方案1】:

    在模态中更改为:--

    旅行模式

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-09
      • 2011-01-24
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多