0

我有一个模型:

class Activity < ActiveRecord::Base
    has_many   :activity_states
end

我想为新的活动状态呈现选项并呈现现有的活动状态。但是,当我使用此 form_for 时:

<%= form_for activity.activity_states.new, :remote => true do |f| %>
    <%= f.hidden_field :state_type, :value => activity_state_type %>
    <%= f.hidden_field :activity_id %>
    <%= f.submit submit_label, :disable_with => 'sending...' %>
<% end %>

为了创建新的临时 activity_state 模型以用作新 activity_states 的基础,它会用nil活动状态污染活动对象,而不是 Activity 具有活动状态:

[#<ActivityState id: 7353, activity_id: 2033, state_type: 0, created_at: "2012-05-31 11:06:50">, 
#<ActivityState id: 7354, activity_id: 2033, state_type: 1, created_at: "2012-05-31 11:06:53">, 
#<ActivityState id: 7355, activity_id: 2033, state_type: 2, created_at: "2012-05-31 11:06:59">]

由于以下原因,它还具有几个nil附加在中间渲染的这些 activity_state 对象.new

#<ActivityState id: nil, activity_id: 2033, state_type: nil, created_at: nil>

导致:

[#<ActivityState id: 7353, activity_id: 2033, state_type: 0, created_at: "2012-05-31 11:06:50">, 
#<ActivityState id: 7354, activity_id: 2033, state_type: 1, created_at: "2012-05-31 11:06:53">, 
#<ActivityState id: 7355, activity_id: 2033, state_type: 2, created_at: "2012-05-31 11:06:59">,
#<ActivityState id: nil, activity_id: 2033, state_type: nil, created_at: nil>,
#<ActivityState id: nil, activity_id: 2033, state_type: nil, created_at: nil>]

然后,当我遍历活动的活动状态并渲染它们时,事情就会变得混乱。我尝试了一种巧妙的方法来解决这个问题:<% activity.activity_states.pop %>在每个 form_for 之后,但这在 Heroku 上的生产中不起作用,因为它抱怨试图修改冻结的数组。

请对这样做的“正确”方式有任何想法吗?我知道我在这里没有理解一些非常基本的东西,也知道我通过为 id 字段插入一个隐藏字段(然后可以被恶意用户操纵)打开了一个漏洞。

4

1 回答 1

0

到目前为止,我有一个解决方案,在 的show方法中activity controller,包括:

@new_activity_state = @activity.activity_states.new
@activity.activity_states.pop

并在部分视图中(我将@activity其作为局部变量传递activity):

<% new_activity_state = @new_activity_state || activity.activity_states.new %>
<%= form_for new_activity_state, :remote => true do |f| %>
    <%= f.hidden_field :state_type, :value => activity_state_type %>
    <%= f.hidden_field :activity_id %>
    <%= f.submit submit_label, :disable_with => 'sending...' %>
<% end %>

Heroku 的生产环境现在不反对 .pop,这很棒 :D 但是有更好的方法吗?

于 2012-05-31T14:46:57.880 回答