Ruby on Rails Association with model many-to-many -



Ruby on Rails Association with model many-to-many -

i`m beginner ror , trying handle many-many association

i handled relationship between models , migration

trip model

class trip < activerecord::base has_many :relationships has_many :topics, through: :relationships end

user model

class user < activerecord::base has_many :relationships has_many :trips, through: :relationships end

relationship model

class relationship < activerecord::base belongs_to :user belongs_to :trip end

my migration

class createrelationships < activerecord::migration def alter create_table :relationships |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 |format| if @user.save format.html { redirect_to @user, notice: 'user 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 |format| if @user.update(user_params) format.html { redirect_to @user, notice: 'user 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 |format| format.html { redirect_to users_url, notice: 'user 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

i don`t know how assign trip user , write assign in controller or in form ??

@user.trips << @trip not work

changed in modal :--

trip model

class trip < activerecord::base has_many :relationships has_many :users, through: :relationships end

user model

class user < activerecord::base has_many :relationships has_many :trips, through: :relationships end

and seek that:-

@user.trips << @trip

ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-4

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -