![](/img/trans.png)
[英]How to make simple_form do what I want with accepts_nested_attributes_for
[英]Issues with Simple_form and accepts_nested_attributes_for
我對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'
這是frequencys_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
我可以從相關頻率的角度編輯課程,但是我有一些奇怪的行為:
我不確定這是否歸因於belongs_to模型上的accepts_nested_attributes_for,因為我通常在has_many模型中看到它。
滑軌5 5.2.2
simple_form 4.1.0
拜托,你能幫我嗎?
謝謝。
render :show OR render :index
.update
, .save
方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.