在保留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

相关问答

更多

Rx.Observable.interval,每个事件的间隔不同(Rx.Observable.interval with different interval for each event)

有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 multiple...

间隔函数在oracle中(interval function in oracle)

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...

1小时后如何选择行?(How to select rows be create after 1 hour?)

也许你想要这样的东西: 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 several averages of an 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`) b...

mysql,查询间隔错误(mysql, error in query interval)

您只能在日期计算功能中使用间隔。 您的查询必须如下所示: 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 wro...

phpMyAdmin事件错误#1542间隔太大(phpMyAdmin event error #1542 interval too big)

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_HO...

选择按HOUR()分组的时间序列(Select time series grouped by HOUR() with wrap around)

一种方法使用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...

Postgresql,选择输出结果+1小时(Postgresql, output result from select with +1 hour)

您可以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)...

Zenoss MySQL查询 - 每小时事件(Zenoss MySQL Query - Events per hour)

将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.statu...

查询以至少一个小时的间隔选择相同的事件代码(Query to select same event code with at least one hour interval)

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

相关文章

更多

Guava Objects类详解

Objects.toStringHelper(s1)

Rails常用插件

测试驱动 rspec-rails:BDD测试框架 初始化:rails generate ...

rails页面文件html.erb如何访问ActiveRecord的资源

一 rails页面文件html.erb如何访问ActiveRecord(model资源)的资源 我的 ...

Rails中的路由功能是如何对应的?

我才开始接触ROR,我是参照agile web development with rails这本书学习 ...

Rails 风格指导

感谢译者。 本页用于介绍 Ruby 社区首推的Rails代码编写风格,翻译来自:https://git ...

rails save问题数据库表主键必须是id吗?

我现在做的RAILS工程表的主键不是id,更新时怎么处理? 就是update的时候,rails的是先用 ...

Rails设置环境变量

目前接触的环境变量分为2种,这里以sunspot中设置solr url为例 1. ENV['SOLR_ ...

在Rails中如何打开一个外部URL,并得到该URL的返回结果。

需要开发一个接口程序,外部程序提供了一个URL的接口,即访问一个URL,最终会得到相应的执行结果。 ...

請問:Rails該如何存取SQL2000中的圖像字段

我做了一個Rails應用已連接好SQL2000,其中SQL2000的一張表中有一個image類型的字段 ...

如何在javascript中写rails的helper代码

如果在模板中这样写 &lt;SCRIPT language=JavaScript&gt; var ...

最新问答

更多

python的访问器方法有哪些

使用方法: class A(object): def foo(self,x): #类实例方法 print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(cls,x): #类方法 print "executing class_foo(%s,%s)"%(cls,x) @staticmethod def static_foo(x): #静态方法 print "executing static_foo(%s)"%x调用方法: a =

使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)

我认为你必须将两个TableGetway传递给UserTable构造。 你必须改变Module.php看看: public function getServiceConfig() { return array( 'factories' => array( 'User\Model\UserTable' => function($sm) { $userTableGateway = $sm->get('UserTable

透明度错误IE11(Transparency bug IE11)

这是一个渲染错误,由使用透明度触发,使用bootstrap用于在聚焦控件周围放置蓝色光环的box-shadow属性。 可以通过添加以下类覆盖来解决它。 .form-control:hover { -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,255,1); -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,255,1); box-shadow: 0px 0px 4px 0px rgba(0,0,255,1)

linux的基本操作命令。。。

ls 显示目录 mkdir 建立目录 cd 进入目录

响应navi重叠h1和nav上的h1链接不起作用(Responsive navi overlaps h1 and navi links on h1 isn't working)

将z-index设置为.main-nav这将解决您的重叠问题 .main-nav { position:relative; z-index:9; } set z-index to .main-nav This will fix your overlaping issue .main-nav { position:relative; z-index:9; }

在C中读取文件:“r”和“a +”标志的不同行为(Reading a File in C: different behavior for “r” and “a+” flags)

这是因为模式规范"a"打开一个文件以便追加,文件指针在末尾。 如果您尝试从此处读取,则由于文件指针位于EOF,因此没有数据。 您应该打开"r+"进行阅读和写作。 如果在写入之前读取整个文件,则在写入更多数据时,文件指针将正确定位以追加。 如果这还不够,请探索ftell()和fseek()函数。 That is because the mode spec "a" opens a file for appending, with the file pointer at the end. If you

NFC提供什么样的带宽?(What Kind of Bandwidth does NFC Provide?)

支持空中接口的数据速率是一回事。 在消除协议开销,等待eeprom写入以及所有需要时间的其他内容之后,您看到的数据速率是完全不同的故事。 长话短说,从标签读取或进行对等传输时的实际数据速率峰值约为2.5千字节/秒。 取决于具体的标签或对等技术,它可能比这慢很多。 The supported data-rates of the air-interface are one thing. The data-rate that you see after removing protocol overhe

元素上的盒子阴影行为(box-shadow behaviour on elements)

它看起来像只在Windows上的Chrome的错误。 我在Google Canary (Chrome 63)中也进行了测试,问题依然存在,所以有可能它不会很快修复。 这个问题是由overflow: auto引起的overflow: auto ,在你的情况下,它可以很容易地通过删除或设置为可见(默认)来解决。 但是 ,将鼠标悬停在右侧(顶部和底部)时,会出现滚动条。 一个解决方案可以设置overflow: hidden的身体,所以预期的结果是所需的。 我想指出,这不是一个很好的解决方案,但我建议暂

Laravel检查是否存在记录(Laravel Checking If a Record Exists)

这取决于您是否要以后与用户合作,或仅检查是否存在。 如果要使用用户对象(如果存在): $user = User::where('email', '=', Input::get('email'))->first(); if ($user === null) { // user doesn't exist } 如果你只想检查 if (User::where('email', '=', Input::get('email'))->count() > 0) { // user found

设置base64图像的大小javascript - angularjs(set size of a base64 image javascript - angularjs)

$scope.getData= function () { var reader = new FileReader(); reader.onload = $('input[type=file]')[0].files; var img = new Image(); img.src =(reader.onload[0].result); img.onload = function() { if(this.width > 640