Rails:创建一个添加另一个引用模型的表单



我有一个评级表,其中包含一个解释字段(文本(。我想要一个创建两个条目的表单(在SasRating和TextContent中(。

我的代码:

迁移率:

class CreateSasRatings < ActiveRecord::Migration[7.0]
def change
create_table :sas_ratings do |t|
t.string :rating
t.references :explanation
t.references :sas, null: false, foreign_key: true
t.timestamps
end
end
end
class CreateTextContents < ActiveRecord::Migration[7.0]
def change
create_table :text_contents do |t|
t.text :originaltext
t.references :originaltext_language
t.timestamps
end
end
end

型号:

class SasRating < ApplicationRecord
belongs_to :explanation, :class_name => :TextContent
belongs_to :sas
end
class TextContent < ApplicationRecord
belongs_to :originaltext_language, :class_name => "Language"
end

控制器:

class SasRatingsController < ApplicationController
def new
@sas = Sas.find(params[:id])
@sasrating = SasRating.new
end
def create
@sasrating = SasRating.new(sas_rating_params)
@sasrating.create_explanation(originaltext: sas_rating_params[:explanation], originaltext_language: sas_rating_params[:originaltext_language] )
@sasrating.save!
flash[:notice] = "SAS Rating was created successfully."
redirect_to sas_path(sas_rating_params[:sas])
rescue => e
logger.error(e.to_s)
flash.now[:danger] = "SAS Rating could not be saved: #{e.to_s}"
render 'new'
end
private
def set_sasrating
@sas = SasRating.find(params[:id])
end
def sas_rating_params
params.require(:sas_rating).permit(:rating, :explanation, :language, :sas_id)
end
end

new.html.erb:

<%= form_with model: @sasrating, local: true do |f| %>
<p> 
<%= f.label :rating, class: "form-label" %><br/> 
<%= f.number_field :rating, class: "form-control" %>
</p>
<p>
<%= fields_for :explanation, @sasrating.explanation do |e| %>
<%= e.label :explanation, class: "form-label" %><br/> 
<%= e.text_field :originaltext, class: "form-control" %>
<%= e.hidden_field :originaltext_language, :value => 2 %>
<% end %>
</p>
<p>
<%= f.hidden_field :sas_id, :value => params[:id] %>
<%= f.submit "submit", class: "btn btn-primary" %> 
</p>
<% end %>

目前,它正在保存SasRating,但没有说明。我做错了什么?

提前谢谢。

要在SasRating模型中创建解释对象,您需要使用accepts_nested_attributes_for,例如。accepts_nested_attributes_for :explanation

相关内容

  • 没有找到相关文章

最新更新