【发布时间】:2019-02-27 16:41:17
【问题描述】:
我对 RoR 很陌生,如果我说的不正确,很抱歉。
我有这些模型。
class Course < ApplicationRecord
has_many :frequencies, inverse_of: :course
belongs_to :subject, optional: true
validates :start_date, presence: true
end
class Frequency < ApplicationRecord
belongs_to :user
belongs_to :course
validates :course, presence: true
validates_presence_of :course
accepts_nested_attributes_for :user, :course
has_many_attached :docs
end
课程和频率之间的关系是 1:N,但最后,我将其用作 1:1(定义模型后发生了变化)。
这是视图 app/views/frequencies/show.html.haml
= simple_form_for @frequency, :url => frequencies_update_path(:id => @frequency.id) do |f|
.panel.panel-primary
.panel-heading
%h4.panel-title= t 'frequencies.upd_frequency'
.panel-body
= f.simple_fields_for :user do |u|
.row
.col-md-4
= u.label t 'frequencies.first_name'
.col-md-4
= u.input :first_name, :label => false, :disabled => true, :input_html => {:id => 'first_name'}
.row
.col-md-4
= u.label t 'frequencies.last_name'
.col-md-4
= u.input :last_name, :label => false, :disabled => true, :input_html => {:id => 'last_name'}
-#= u.hidden_field :id, value: @user_id
.panel.panel-primary
.panel-heading
%h4.panel-title= t 'frequencies.course'
.panel-body
= f.simple_fields_for :course do |u|
.row
.col-md-4
= u.label t 'frequencies.course_start_date'
.col-md-4
= u.input :start_date, :label => false, :disabled => (@frequency.validated? ? true : false), :input_html => {:id => 'course_start_date'}
.
.
.
= f.submit t('button.save'), :class => 'btn btn-primary ' + (current_user.role == $admin_role && @frequency.validated? ? 'disabled' : '')
= link_to t('button.cancel'), request.referer.present? ? request.referer : frequencies_index_path, :class => 'btn btn-default'
这是 frequencies_controller.rb
的一部分def update
@frequency = Frequency.find params[:id]
@course = Course.find @frequency.course_id
if over_max_hours_in_a_day(frequency_params[:user_attributes][:id], @course)
flash[:danger] = t('flash.max_hours')
render :action => :show and return
end
if @course.update(frequency_params[:course_attributes])
@frequency.docs.attach(frequency_params[:attach][:docs]) if (frequency_params[:attach].present? && frequency_params[:attach][:docs].present?)
flash[:notice] = t('flash.upd')
redirect_to :action => 'index' and return
else
flash[:danger] = @course.errors.full_messages.to_sentence
render :action => :show and return
end
end
def show
@frequency = Frequency.find params[:id]
@subjects = Subject.all
end
我可以从相关频率的角度编辑课程,但我有一些奇怪的行为:
- 当我保存验证过程时,我的错误消息仅显示为 flash 消息,而不是在所涉及的字段下(在其他更简单的视图中,我在字段下也有消息)
- 当我编辑某些课程的字段(从频率视图)并单击保存按钮后,它会调用更新操作,但是,如果它在 over_max_hours_in_a_day if 条件内运行,我将无法停留在同一个视图上修改后的字段已预编译(但我在开头显示操作时加载了类似的字段)
- 当我在上一次编辑失败后按下取消按钮时,我会留在同一页面上,而不是返回上一个视图(索引视图)
我不确定这是否是由于belongs_to 模型上的accepts_nested_attributes_for,因为我通常在has_many 模型中看到它。
Rails 5 5.2.2
simple_form 4.1.0
拜托,你能帮帮我吗?
谢谢。
【问题讨论】:
-
有什么帮助吗?我找不到出路...