添加关系编辑中的问题,而不是新的
问题描述:
我试图建立一个“事件”,允许用户动态地添加笔记(文本字段)与一些JavaScript的窗体。因此,当他们点击表单中的“添加注释”按钮时,会弹出一个文本框并添加注释。如果他们再次点击它,则会显示另一个字段。到目前为止,这在创建新事件时工作得很好,但是当我编辑事件并添加新字段时,它没有选择incident_note和user之间的关系。添加关系编辑中的问题,而不是新的
例如,以下是我在创建新事件时看到的内容。
INSERT INTO "incident_notes" ("created_at", "updated_at", "user_id", "note", "incident_id") VALUES('2010-07-02 14:07:42', '2010-07-02 14:07:42', 2, 'A Note', 8)
正如您所看到的,user_id字段有一个分配给它的编号。但是,在编辑过程中,当我添加另一个注释时,会发生以下情况:
INSERT INTO "incident_notes" ("created_at", "updated_at", "user_id", "note", "incident_id") VALUES('2010-07-02 14:09:11', '2010-07-02 14:09:11', NULL, 'Another note', 8)
user_id为NULL。我不知道我做了什么。该代码对于控制器中的“编辑”和“新建”非常相似。
我有以下的模型和关系(只显示相关部分):
class Incident < ActiveRecord::Base
has_many :incident_notes
belongs_to :user
end
class IncidentNote < ActiveRecord::Base
belongs_to :incident
belongs_to :user
end
class User < ActiveRecord::Base
has_many :incidents
has_many :incident_notes
end
这是新形式的相关部分(编辑基本上是相同的):
<% form_for([@customer,@incident]) do |f| %>
<p>
<% f.fields_for :incident_notes do |inf| %>
<%= render "incident_note_fields", :f => inf %>
<% end %>
<p><%= link_to_add_fields "Add Note", f, :incident_notes %></p>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
这里是事件控制器中的创建和更新方法。
def create
@incident = @customer.incidents.build(params[:incident])
@incident.capc_id = generate_capc_id
for inote in @incident.incident_notes
(inote.user = current_user) if (inote.user == nil)
end
respond_to do |format|
if @incident.save #etc
end
def update
@incident = @customer.incidents.find(params[:id])
for inote in @incident.incident_notes
(inote.user = current_user) if (inote.user == nil)
end
respond_to do |format|
if @incident.update_attributes(params[:incident])
#etc
end
可能有更好的方法来做到这一点,但你可以在“创造”的方法,我不得不在incident_note用户字段手动设置为当前用户看到。这工作正常,但似乎没有在更新方法中工作。
任何想法,建议和帮助将被大大支持!我现在很困难。 :)
答
我建议你没有直接属于用户的incident_notes。换句话说,用户有很多事件,事件中有很多事件记录。
class Incident < ActiveRecord::Base
has_many :incident_notes
belongs_to :user
end
class IncidentNote < ActiveRecord::Base
belongs_to :incident
end
class User < ActiveRecord::Base
has_many :incidents
has_many :incident_notes, :through => :incident
end
用户的事件笔记,然后通过她的事件模型
的问题,这是我希望用户能够为其他用户所拥有的事件创建注释获得。如果我理解正确,这不会允许,对吧? – Magicked 2010-07-02 17:06:46
不,我相信只要事件的所有权保留在原始用户身上,仍然可以工作。用户B“有权限”更新或为用户A创建备注的问题是特定于应用程序的概念,并且应用程序不会通过数据库架构强制实施。只要允许控制器操作允许“current_user”查找属于另一个用户的事件,您应该没问题 – bjg 2010-07-02 20:43:06