我有两个模型:Activity
和Comment
。 Comment
belongs_to :activity
和Activity
has_many :comments
。对于建筑活动,我已经遵循了Railscast (Activity feed from scratch)
所以,我正在使用activity_presenter.rb
class ActivityPresenter < SimpleDelegator
attr_reader :activity
def initialize(activity, view)
super(view)
@activity = activity
end
def render_activity
div_for activity do
link_to((gravatar_for activity.user, {size: 20}) + activity.user.name, activity.user) + ' ' + render_partial
end
end
def render_partial
locals = {activity: activity, presenter: self}
locals[activity.trackable_type.underscore.to_sym] = activity.trackable
render partial_path, locals
end
def partial_path
partial_paths.detect do |path|
lookup_context.template_exists? path, nil, true
end || raise("No partial found for activity in #{partial_paths}")
end
def partial_paths
[
"activities/#{activity.trackable_type.underscore}/#{activity.action}",
"activities/#{activity.trackable_type.underscore}",
"activities/activity"
]
end
end
使用_activities_feed.rb
条件呈现@activities.each do |activity|
部分。
在这部分我有3个街区:
activity
form for activity
用于更新目的activity.comments
阻止each do |comment|
activity.comments.new
(表格)这是一个问题。我需要渲染Activity.comments
和表单以便从comments
控制器创建新评论,因为我在一个视图中有2个表单,有2个submit
按钮,它们调用2 update
或create
行动。当然,我需要它来改善应用程序逻辑。
但是我无法从activity
发送@activities.each do |activity|
comments_controller
,我在这部分地方使用了@activity = Activity.find(params[:id])
。
我尝试将@comment = Activity.comments.new(params[:activity_id])
,@comments = Activity.comments.all
,activities
添加到comments
和activity
控制器,并将@activity
更改为{ {1}}和activity.comments.new
到@comment
。但它没有帮助。我想,我不理解控制器之间交互的基本逻辑,但找不到我的错误。
因此,我的activities_controller
index
行动是:
@activities = Activity.order('updated_at DESC')
在comments_controller
我只有create
和destroy
行动,这些行动都可以。
感谢您的帮助!
UPD:
这是我的_activities_feed.rb
结构:
<% @activities.each do |activity| %>
<%= form_for activity, remote: true do |a| %>
<%= ActivityPresenter.new(activity, self).render_activity %>
.
.
.
<%= link_to ... class: 'add_comment', remote: true %> # Shows activity.new.comment form
<%= link_to ... 'Edit' ... %> # edit activity link
<%= a.submit 'Update' %> # first submit button for submitting activity changes
.
.
.
<% activity.comments.each do |comment| %> # activity.comments block
<%= comment.text %>
<%= link_to comment.user.name, comment.user %>
<% end %>
.
.
.
<%= form_for activity.comments.new, remote: true do |f| %> # form for adding comment
<%= f.text_area :text, 'rows' => '2', class: 'comment_text' %>
<%= f.button 'Cancel', class: 'btn comment_cancel', type: 'button' %>
<%= f.submit 'Post', class: 'btn btn-primary', controller: 'comments' %> # second submit button
<%= f.hidden_field :activity_id, value: activity.id %>
<% end %>
<% end %>
<% end %>
答案 0 :(得分:0)
问题出在嵌套表格上。因此,当我提交表单以进行新评论时,它还提交了更新活动的父表单。