gpt4 book ai didi

mysql - 在 Rails 中嵌套用户特定的表单

转载 作者:行者123 更新时间:2023-11-30 22:54:07 24 4
gpt4 key购买 nike

我正在尝试构建一个嵌套表单供我的 Devise 用户填写并稍后更新。该表格由两个模型组成;一个用于问题,另一个用于用户。我的 Controller 看起来像这样:

class LegalFormsController < ApplicationController
before_action :set_legal_form, only: [:show, :edit, :update, :destroy, :answers]

respond_to :html

def index
@legal_forms = LegalForm.all
respond_with(@legal_forms)
end

def show
respond_with(@legal_form)
end

def new
@legal_form = LegalForm.new
respond_with(@legal_form)
end

def edit
end

def create
@legal_form = LegalForm.new(legal_form_params)
@legal_form.save
respond_with(@legal_form)
end

def update
@legal_form.update(legal_form_params)
respond_with(@legal_form)
end

def destroy
@legal_form.destroy
respond_with(@legal_form)
end

def answers
@users = User.all
@questions = @legal_form.questions
end

private

def set_legal_form
@legal_form = LegalForm.find(params[:id])
end

def legal_form_params
params.require(:legal_form).permit(:name,
:questions_attributes => [:id, :content,
:answers_attributes =>[:id, :content, :participant_id]
])
end
end

答案的 View (当前)如下:

<h1><%= @legal_form.name %> Answers</h1>

<%= form_for(@legal_form) do |f| %>
<% @users.each do |user| -%>
<h3><%= user.id %></h3>
<table>
<thead>
<tr>
<td>Questions</td>
<td>Answer</td>
</tr>
<tbody>
<% @questions.each do |question| -%>
<tr>
<td><%= question.content %></td>
<td>
<%= f.fields_for :questions, question do |q| -%>
<%=q.fields_for :answers, question.answers.find_or_initialize_by(user: @user) do |a| -%>
<%= a.text_area :content %>
<%= a.hidden_field :user_id, :value => current_user %>
<% end -%>
<% end -%>
</td>
</tr>
<% end -%>
</tbody>
</table>
<% end -%>
<div class="actions">
<%= f.submit %>
</div>
<% end =%>

如您所见,这当前会为所有用户显示所有问题/答案。
我的问题有两个:

  1. 我该如何设置它以只显示当前用户?
  2. 使用这条线 <%= a.hidden_field :user_id, :value => current_user %> ,我正在尝试为保存到 user_id 下的答案数据库中的每个答案提供当前用户 ID。但是,它似乎没有用。我可能遗漏了什么?

非常感谢您对此提供的任何帮助!

应要求,以下是我的模型关联

class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
end

class LegalForm < ActiveRecord::Base
has_many :questions

accepts_nested_attributes_for :questions
end

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :answers
has_many :questions, through: :answers
end

class Question < ActiveRecord::Base
belongs_to :legal_form
has_many :answers
has_many :users, through: :answers

accepts_nested_attributes_for :answers
end

最佳答案

您可以像这样设置 user_id 值

<%= f.hidden_field :user_id, value: current_user.id %>

关于mysql - 在 Rails 中嵌套用户特定的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com