简体   繁体   中英

RoR: Save information from 3 models at same time

I am trying to make it so that when I save an answer, I also save the prop_id that is associated with that answer.

I have a nested route relationship so that each prop (stands for proposition or bet) has a an associated answer like this: http://localhost:3000/props/1/answers/new .

Right now, when I save an answer, I save the answer choice and the user_id who created the answer. I need to save also the prop that is associated with the answer.

Answers Controller:

class AnswersController < ApplicationController
  attr_accessor :user, :answer

  def index

  end

  def new
    @prop = Prop.find(params[:prop_id])

    @user = User.find(session[:user_id])

    @answer = Answer.new

  end

  def create
    @prop = Prop.find(params[:prop_id])
    @user = User.find(session[:user_id])
    @answer = @user.answers.create(answer_params)

    if @answer.save 

    redirect_to root_path

    else
    render 'new'
    end


  end


  def show
    @answer = Answer.find params[:id]

  end
end

private
def answer_params
  params.require(:answer).permit(:choice, :id, :prop_id)
end

Answer Model

class Answer < ActiveRecord::Base
  belongs_to :prop
  belongs_to  :created_by, :class_name => "User", :foreign_key => "created_by"
  has_many :users

end

Prop Model

class Prop < ActiveRecord::Base
  belongs_to :user
  has_many :comments
  has_many :answers
end

User Model

class User < ActiveRecord::Base
  has_many :props
  has_many :answers
  has_many :created_answers, :class_name => "Answer", :foreign_key => "created_by"
  before_save { self.email = email.downcase }
  validates :username, presence: true, uniqueness: {case_sensitive: false}, length: {minimum: 3, maximum: 25}
  has_secure_password
end

Just modify your code a little bit, and it will work:

def create
  @user        = User.find(session[:user_id])
  @prop        = @user.props.find_by(id: params[:prop_id])
  @answer      = @user.answers.build(answer_params)
  @answer.prop = @prop

  # Modify @user, @prop or @answer here

  # This will save @user, @prop & @answer
  if @user.save
    redirect_to root_path
  else
    render 'new'
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM