我试图让它成为当我保存答案时,我还保存与该答案相关联的prop_id。
我有一个嵌套的路线关系,所以每个道具(代表命题或下注)都有一个相关的答案,如:http://localhost:3000/props/1/answers/new。
现在,当我保存答案时,我保存了答案选项和创建答案的user_id。我还需要保存与答案相关的道具。
答案控制器:
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
答案模型
class Answer < ActiveRecord::Base
belongs_to :prop
belongs_to :created_by, :class_name => "User", :foreign_key => "created_by"
has_many :users
end
道具模型
class Prop < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :answers
end
用户模型
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
答案 0 :(得分:0)
只需稍微修改一下代码,就可以了:
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