首页 \ 问答 \ Rails中的模型4在不包含它们时验证可选关联(Model in Rails 4 validating optional associations when they are not included)

Rails中的模型4在不包含它们时验证可选关联(Model in Rails 4 validating optional associations when they are not included)

我在Rails应用程序中有一个嵌套表单,用于事件模型,允许用户在事件重现时指定Recurrence(另一个模型)的字段。 在创建事件时一切正常,但是当事件不再发生时(因此不想保存关系),它会在更新事件时给出错误。 我设置了重复设置来验证字段“频率”是否存在。 当没有重复时,此字段留空,但表单仍然会回来并说频率需要在那里。 帮帮我?

class Event < ActiveRecord::Base
  has_one :recurrence
  accepts_nested_attributes_for :recurrence
end

class Recurrence < ActiveRecord::Base
  belongs_to :event
  validates :frequency, :presence => true
end

来自事件控制器

def event_params
  params.require(:event).permit(
    :name, :start, :duration, :unit, :location, :description, :major,
    recurrence_attributes: [ :frequency, :end ])
end

def update
  @event = Event.find(params[:id])

  if @event.recurrence && !params.has_key?(:has_recurrence)
    @event.recurrence.destroy 
  end

  if @event.update(event_params)
    redirect_to event_path(@event)
  else
    render 'edit'
  end
end

您将注意到它正在检查是否存在名为“has_recurrence”的参数 - 这是我在模型外部的表单中的复选框标记,用于确定是否应为事件保存重复。 如果用户选中该框,表单将尝试保存重复,但如果他们不选中该框,表单将不会保存重复(至少这是个想法)。

问题是当我提交表单来编辑事件时,当事件没有重复出现并且未检查has_recurrence框时,它仍然会尝试验证重复发生并给我一个验证错误:

Recurrence frequency can't be blank

更新我已根据以下答案更新了我的重复模型以有条件地验证:

class Recurrence < ActiveRecord::Base
  belongs_to :event

  validates :frequency, :presence => true, :if => :has_recurrence

  def has_recurrence=( yesorno=false )
    @has_recurrence = yesorno
  end

  def has_recurrence
    @has_recurrence ||= false
  end
end

我的事件控制器中的更新如下......

def update

  @event = Event.find(params[:id])

  if @event.recurrence && !@has_recurrence 
    @event.recurrence.destroy
  end

  if @event.update(event_params)
    redirect_to event_path(@event)
  else
    flash[:notice] = @event.errors
    render 'edit'
  end
end

并且视图包含以下内容以检查是否存在重复:

<div class="form-group">
  <%= check_box_tag "has_recurrence", nil, false %> Is this a recurring event? (must check to save recurrence)
</div>
<%= f.fields_for :recurrence do |builder| %>
  <%= render 'recurrence_fields', f: builder %>
<% end %>

现在,当没有检查重复时我没有得到验证错误,但是重复发生是保存到数据库(所有内容都是空白但是event_id)


I have a nested form in my Rails app for an Events model that allows the user to specify fields for Recurrence (another model) when the event recurs. Everything is working fine on creating the event, but it's giving me errors on updating the event when the event does not recur (and therefore does not want to save the relationship). I have recurrence set up to validate that the field "frequency" is present. When there is no recurrence, this field is left blank, but the form still kicks back and says that frequency needs to be there. Help?

class Event < ActiveRecord::Base
  has_one :recurrence
  accepts_nested_attributes_for :recurrence
end

class Recurrence < ActiveRecord::Base
  belongs_to :event
  validates :frequency, :presence => true
end

from Events controller

def event_params
  params.require(:event).permit(
    :name, :start, :duration, :unit, :location, :description, :major,
    recurrence_attributes: [ :frequency, :end ])
end

def update
  @event = Event.find(params[:id])

  if @event.recurrence && !params.has_key?(:has_recurrence)
    @event.recurrence.destroy 
  end

  if @event.update(event_params)
    redirect_to event_path(@event)
  else
    render 'edit'
  end
end

You will note that it is checking for the presence of a param called "has_recurrence" - This is a checkbox tag that I have in the form, outside of the model, to determine whether or not a recurrence should be saved for the event. If the user checks the box, the form will attempt to save the recurrence but if they do not check the box, the form will not save the recurrence (at least that's the idea).

The problem is that when I submit the form to edit an event, when the event is not recurring and the has_recurrence box is not checked, it still attempts to validate the recurrence and gives me back a validation error:

Recurrence frequency can't be blank

UPDATE I have updated my recurrence model to validate conditionally, based on the answer below:

class Recurrence < ActiveRecord::Base
  belongs_to :event

  validates :frequency, :presence => true, :if => :has_recurrence

  def has_recurrence=( yesorno=false )
    @has_recurrence = yesorno
  end

  def has_recurrence
    @has_recurrence ||= false
  end
end

And the update in my Events Controller is as follows...

def update

  @event = Event.find(params[:id])

  if @event.recurrence && !@has_recurrence 
    @event.recurrence.destroy
  end

  if @event.update(event_params)
    redirect_to event_path(@event)
  else
    flash[:notice] = @event.errors
    render 'edit'
  end
end

And the view contains the following to check if there is a recurrence:

<div class="form-group">
  <%= check_box_tag "has_recurrence", nil, false %> Is this a recurring event? (must check to save recurrence)
</div>
<%= f.fields_for :recurrence do |builder| %>
  <%= render 'recurrence_fields', f: builder %>
<% end %>

And now, when recurrence is not checked I do not get a validation error, but the recurrence is saving to the database (with everything blank but the event_id)


原文:https://stackoverflow.com/questions/33737341
更新时间:2022-02-05 20:02

最满意答案

提供的代码的问题在这里:

<xsl:value-of select="$Content1"/>

这将输出$Content1的顶级节点(如果它包含文档)的所有文本节点后代的串联或其第一个元素或文本子节点的字符串值(如果它是XML片段)。

你需要使用

<xsl:copy-of select='$pContent1'>

代替

<xsl:value-of select='$pContent1'>

这正确地复制了$pContent1所有子节点

以下是更正后的转换

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <xsl:call-template name="MainMasterPage">
    <xsl:with-param name="pContent1">
      <h1>Title</h1>
      <p>More Content</p>
      <xsl:call-template name="SomeOtherTemplate"/>
     </xsl:with-param>
   </xsl:call-template>
</xsl:template>

<xsl:template name="MainMasterPage">
  <xsl:param name="pContent1"/>
  <html>
    <!-- bunch of stuff here -->
    <xsl:copy-of select="$pContent1"/>
  </html>
</xsl:template>

 <xsl:template name="SomeOtherTemplate">
   <h2>Hello, World!</h2>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于任何XML文档(未使用)时,将生成所需的正确结果

<html>
   <h1>Title</h1>
   <p>More Content</p>
   <h2>Hello, World!</h2>
</html>

The problem with the provided code is here:

<xsl:value-of select="$Content1"/>

This will output either the concatenation of all text-nodes descendents of the top node of $Content1 (if it contains a document) or the string value of its first element or text child (if it is an XML fragment).

You need to use

<xsl:copy-of select='$pContent1'>

instead of

<xsl:value-of select='$pContent1'>.

This correctly copies all children nodes of $pContent1

Below is a corrected transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <xsl:call-template name="MainMasterPage">
    <xsl:with-param name="pContent1">
      <h1>Title</h1>
      <p>More Content</p>
      <xsl:call-template name="SomeOtherTemplate"/>
     </xsl:with-param>
   </xsl:call-template>
</xsl:template>

<xsl:template name="MainMasterPage">
  <xsl:param name="pContent1"/>
  <html>
    <!-- bunch of stuff here -->
    <xsl:copy-of select="$pContent1"/>
  </html>
</xsl:template>

 <xsl:template name="SomeOtherTemplate">
   <h2>Hello, World!</h2>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on any XML document (not used), the wanted, correct result is produced:

<html>
   <h1>Title</h1>
   <p>More Content</p>
   <h2>Hello, World!</h2>
</html>

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。