首页 \ 问答 \ 在保留id的同时避免每个轨道中的空对象(Avoiding empty objects in rails each while preserving ids)

在保留id的同时避免每个轨道中的空对象(Avoiding empty objects in rails each while preserving ids)

以下模板基于http://guides.rubyonrails.org/getting_started.html上的rails教程

我正在创建内联的“real_comments”以避免由@ article.comments.build形式创建的额外空注释,但是当我尝试删除它时,这会导致错误,因为注释ID丢失了。

No route matches [DELETE] "/articles/2/comments"

是否有可能删除构建创建的额外注释,同时维护用于对注释执行操作的索引? 我通过玩弄自己想出了real_comments解决方案,所以我毫不怀疑我正在做一些非常不受影响的问题,导致问题

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>
<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>
<%#How to copy an array in ruby %>
<% real_comments = @article.comments.map do |e|
  e.dup
end %>

<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |f| %>
    <p>
      <%= f.label :commenter %>
      <%= f.text_field :commenter %>
    </p>
    <p>
      <%= f.label :body %>
      <%= f.text_area :body %>
    </p>
    <p>
      <%= f.submit %>
    </p>
<% end %>

<h2>Comments:</h2>
<% real_comments.each do |comment| %>
    <p>
      <strong>Commenter:</strong>
      <%= comment.commenter %>
    </p>

    <p>
      <strong>Comment:</strong>
      <%= comment.body %>
    </p>

    <%= link_to 'Destroy Comment', [comment.article, comment], method: :delete, data: {confirm: 'Are you sure?'} %>
<% end %>

<%= link_to 'Edit', edit_article_path(@article) %>
<%= link_to 'Back', articles_path %>

The following template is based off of the rails tutorial at http://guides.rubyonrails.org/getting_started.html

I'm creating the "real_comments" inline to avoid an extra empty comment created by the form @article.comments.build however this causes an error as the comment id is missing when I try to delete it.

No route matches [DELETE] "/articles/2/comments"

Is it possible to strip out the extra comment created by build while maintaining the index for performing operations on the comment by id? I came up with the real_comments solution myself by playing around so I have no doubt I'm doing something very un-rails which is causing the issue

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>
<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>
<%#How to copy an array in ruby %>
<% real_comments = @article.comments.map do |e|
  e.dup
end %>

<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |f| %>
    <p>
      <%= f.label :commenter %>
      <%= f.text_field :commenter %>
    </p>
    <p>
      <%= f.label :body %>
      <%= f.text_area :body %>
    </p>
    <p>
      <%= f.submit %>
    </p>
<% end %>

<h2>Comments:</h2>
<% real_comments.each do |comment| %>
    <p>
      <strong>Commenter:</strong>
      <%= comment.commenter %>
    </p>

    <p>
      <strong>Comment:</strong>
      <%= comment.body %>
    </p>

    <%= link_to 'Destroy Comment', [comment.article, comment], method: :delete, data: {confirm: 'Are you sure?'} %>
<% end %>

<%= link_to 'Edit', edit_article_path(@article) %>
<%= link_to 'Back', articles_path %>

原文:https://stackoverflow.com/questions/41728920
更新时间:2024-04-23 22:04

最满意答案

我有点像冒泡的方法。 我在进行递归操作时发现的问题是它们适用于小型集合(想想小于5或10k),然后当你变大时表现得很糟糕。 出于这个原因,我喜欢光标方法,你实际上是在说:“你是否大于标准?是,否。插入或忽略,删除,继续前进。” 这样,您只需对一次和每次一次的项目进行评估,而不是对递归主题的每个变体进行评估。

DECLARE @Temp TABLE 
  (
    id INT 
  , dt DATETIME
  , txt VARCHAR(8)
  , rwn INT
  )

DECLARE @Holder TABLE 
  (
    id INT 
  , dt DATETIME
  , txt VARCHAR(8)
  , Dif int
  )

INSERT INTO @Temp
SELECT *, row_number() over (partition by txt order by dt, id) AS rn
From wt

WHILE EXISTS (SELECT 1 FROM @Temp)
BEGIN
    DECLARE 
      @CurId    INT
    , @CurDt    DATETIME
    , @Curtxt   VARCHAR(8)
    , @LastDate DATETIME
    ;

    SELECT TOP 1 @CurId = Id, @CurDt = Dt, @Curtxt = txt FROM @Temp ORDER BY txt, rwn

    --If there is not entry you need a single entry
    IF NOT EXISTS (SELECT TOP 1 * FROM @Holder)
       BEGIN
          INSERT INTO @Holder VALUES (@CurId, @CurDt, @curtxt, null)
       END
    ELSE
      --if you reset the grouping you need to reset and begin anew
      IF (SELECT rwn FROM @Temp WHERE Id = @CurId) = 1
        BEGIN
            INSERT INTO @Holder VALUES (@CurId, @CurDt, @curtxt, null)
        END
      --if you are going along check the logic for the difference of what the last was compared to the current
      ELSE
        BEGIN
         SELECT TOP 1 @LastDate = dt FROM @Holder ORDER BY id desc

         IF DATEDIFF(HOUR, @LastDate, @CurDt) >= 1
         BEGIN
             INSERT INTO @Holder VALUES (@CurId, @CurDt, @curtxt, DATEDIFF(MINUTE, @LastDate, @CurDt))
         END
        END

    --Delete the running values and loop again
    DELETE @Temp WHERE Id = @CurId
END

Select *
From @Holder

I kind of like a method that is a bubble sort. The problem I have found when doing recursive operations is they work great for small sets(think less than 5 or 10k), then behave horrid when you get larger. For this reason I like a cursor approach were you are essentially saying: "Are you larger than a criteria? Yes, No. Insert or Ignore, Delete, move on." This way you are evaluating over every item once and once only, not every variation of a theme of recursion.

DECLARE @Temp TABLE 
  (
    id INT 
  , dt DATETIME
  , txt VARCHAR(8)
  , rwn INT
  )

DECLARE @Holder TABLE 
  (
    id INT 
  , dt DATETIME
  , txt VARCHAR(8)
  , Dif int
  )

INSERT INTO @Temp
SELECT *, row_number() over (partition by txt order by dt, id) AS rn
From wt

WHILE EXISTS (SELECT 1 FROM @Temp)
BEGIN
    DECLARE 
      @CurId    INT
    , @CurDt    DATETIME
    , @Curtxt   VARCHAR(8)
    , @LastDate DATETIME
    ;

    SELECT TOP 1 @CurId = Id, @CurDt = Dt, @Curtxt = txt FROM @Temp ORDER BY txt, rwn

    --If there is not entry you need a single entry
    IF NOT EXISTS (SELECT TOP 1 * FROM @Holder)
       BEGIN
          INSERT INTO @Holder VALUES (@CurId, @CurDt, @curtxt, null)
       END
    ELSE
      --if you reset the grouping you need to reset and begin anew
      IF (SELECT rwn FROM @Temp WHERE Id = @CurId) = 1
        BEGIN
            INSERT INTO @Holder VALUES (@CurId, @CurDt, @curtxt, null)
        END
      --if you are going along check the logic for the difference of what the last was compared to the current
      ELSE
        BEGIN
         SELECT TOP 1 @LastDate = dt FROM @Holder ORDER BY id desc

         IF DATEDIFF(HOUR, @LastDate, @CurDt) >= 1
         BEGIN
             INSERT INTO @Holder VALUES (@CurId, @CurDt, @curtxt, DATEDIFF(MINUTE, @LastDate, @CurDt))
         END
        END

    --Delete the running values and loop again
    DELETE @Temp WHERE Id = @CurId
END

Select *
From @Holder

相关问答

更多
  • 有generateWithRelativeTime运算符。 官方文档在这里 。 简而言之,操作员允许您指定一个序列,您可以在发出每个值时进行调整。 它类似于for循环,只是值在您选择的时刻异步发出。 例如,同步for循环: for (i=1;i<4; i++) {do something} 可以转换为由100ms,200ms,300ms分隔的值序列 // Generate a value with an absolute time with an offset of 100ms multipled by ...
  • INTERVAL不是一个函数,它是一个引入间隔字面值的关键字,而这个表示数据类型 。 类似于文字TIMESTAMP '2011-05-04 17:18:19'或TIMESTAMP '2011-05-04 17:18:19'正在做的事情。 有关区间文字的详细信息 http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements003.htm#SQLRF00221 http://docs.oracle.com/cd/E11882_01/serv ...
  • 也许你想要这样的东西: SELECT * FROM signup_pending WHERE now() < create_date + '1 hour'::INTERVAL Maybe you want something like that: SELECT * FROM signup_pending WHERE now() < create_date + '1 hour'::INTERVAL
  • 尝试 SELECT avg(`value`) FROM `table` WHERE timestamp >= NOW() - INTERVAL 7 DAY AND timestamp <= NOW() group by concat(date(`timestamp`), case when hour(`timestamp`) between 0 and 7 then 1 when hour(`timestamp`) betwee ...
  • 您只能在日期计算功能中使用间隔。 您的查询必须如下所示: select *, (select max(h.date) from hour_cards as h where h.subordinate_id = hour_cards.subordinate_id and h.date > hour_cards.date and DATE_ADD(h.date, INTERVAL 1 minute) <= hour_cards.date as wrong_en ...
  • Juergen d在评论中基本回答了我的问题。 间隔设置为“EVERY 0 DAY_HOUR”,而在phpmyadmin中,它设置为“EVERY'0_10'DAY_HOUR”。 我之前用'0_10'保存了它,但显然它不再起作用,或者可能永远不会工作(即使事件确实如此)。 我改为“每10小时”,现在它保存得很好。 Juergen d basically answered my question in a comment. The interval was set to "EVERY 0 DAY_HOUR" w ...
  • 一种方法使用date_format() : SELECT HOUR(readAt) pointTime, ROUND(AVG(temperature),1) avgTemp FROM TempReadings WHERE temperature IS NOT NULL AND date_format(readAt, '%Y-%m-%d %h') BETWEEN date_format(now() - interval 25 hour, '%Y-%m-%d % ...
  • 您可以group by以下方式将两列添加到group by : SELECT CONCAT(TO_CHAR(timestamp::timestamp, 'YYYY-MM-DD HH'), ':00:00') as time_from, CONCAT(TO_CHAR(timestamp::timestamp + interval '1 hour', 'YYYY-MM-DD HH'), ':00:00') as time_to, car_id, SUM(km) as d ...
  • 将union放在子查询中,然后使用SUM()将它们添加到一起。 SELECT SUM(c) total FROM (SELECT COUNT(*) c FROM events.history WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3') UNION SELECT COUNT(*) c FROM events.status WHE ...
  • 我有点像冒泡的方法。 我在进行递归操作时发现的问题是它们适用于小型集合(想想小于5或10k),然后当你变大时表现得很糟糕。 出于这个原因,我喜欢光标方法,你实际上是在说:“你是否大于标准?是,否。插入或忽略,删除,继续前进。” 这样,您只需对一次和每次一次的项目进行评估,而不是对递归主题的每个变体进行评估。 DECLARE @Temp TABLE ( id INT , dt DATETIME , txt VARCHAR(8) , rwn INT ) DECLARE @Hol ...

相关文章

更多

最新问答

更多
  • CSS修复容器和溢出元素(CSS Fix container and overflow elements)
  • SQL多个连接在与where子句相同的表上(SQL Multiple Joins on same table with where clause)
  • nginx 80端口反向代理多个域名,怎样隐藏端口的
  • xcode提醒样式,swift 3(xcode alert style, swift 3)
  • 在Chrome控制台中调试JavaScript(debugging javascript in Chrome console)
  • Javascript - 试图围绕自定义事件(Javascript - Trying to wrap my head around custom events)
  • 边栏链接不可点击(Sidebar links aren't clickable)
  • 使用recpatcha gem时如何显示其他表单错误?(How do I display other form errors when using the recpatcha gem?)
  • boost.python避免两次注册内部类,但仍然在python中公开(boost.python Avoid registering inner class twice but still expose in python)
  • Android 现在软件很少吗?以后会多起来吗
  • 如何在ActiveAdmin 0.5.0中为资源全局指定预先加载?(How to specify eager loading globally for a resource in ActiveAdmin 0.5.0?)
  • matlab代码为黄金比例持续分数(matlab code for golden ratio continued fraction)
  • Android浏览器触摸事件位置(Android browser touch event location)
  • 将cURL输出分配给Bash中的变量(Assign output to variable in Bash)
  • 我如何在MVC视图上没有时间获取当前日期(how i can get current date without time on MVC view)
  • sql连接函数(sql join of function)
  • 为什么在Xamarin Media插件中使用ImageSource.FromStream而不是FromFile?(Why use ImageSource.FromStream instead of FromFile in Xamarin Media plugin?)
  • 这段代码是否真的可以防止SQL注入?(Will this code actually work against SQL-injection? [duplicate])
  • 信阳方远计算机学校大专证被国家认可么
  • React / Rails AJAX POST请求返回404(React/Rails AJAX POST request returns 404)
  • Android与php服务器交互(Android interact with php server)
  • 自动刷新QTableWidget可能吗?(Refresh QTableWidget automatically possible?)
  • JVM / Compiler优化对象的未使用属性(optimization of unused properties of object by JVM / Compiler)
  • 插入表格时,乌克兰字符会更改为问号(Ukrainian character change to question mark when insert to table)
  • 在头文件中包含异常类(Including an exception class in a header file)
  • 完成c#中的执行后关闭sqlcmd(Close sqlcmd after finishing executing in c#)
  • 使用软导航栏正确检测屏幕尺寸(Detecting screensize correctly with soft navigation bar)
  • Typescript:从输入更新值(Typescript : update value from input)
  • 如何在执行某些行后仅在断点处停止?(How to only stop at a breakpoint after some line was executed?)
  • 以未定义的元素在JSON中循环(loop in JSON with undefined elements)