我对'想法'有'完整'和'不完整'的链接。我想在没有页面重新加载的情况下切换它们。
这是我目前的代码:
_idea.html.erb partial:
<li id="<%= dom_id(idea) %>">
<%= idea.description %>
<% if idea.completed? %>
<%= link_to "Incomplete", complete_project_idea_path(idea.project, idea), method: :patch, remote: true %>
<% else %>
<%= link_to "Complete", complete_project_idea_path(idea.project, idea), method: :patch, remote: true %>
<% end %>
</li>
这是我的控制器操作(我正在使用嵌套资源):
def complete
@project = Project.find(params[:project_id])
@idea = @project.ideas.find(params[:id])
respond_to do |format|
@idea.toggle_completion!
format.html {redirect_to root_path}
format.js { }
end
end
在idea.rb模型中:
def completed?
!completed_at.blank?
end
def toggle_completion!
if completed?
update_attribute(:completed_at, nil)
else
update_attribute(:completed_at, Time.now)
end
end
Complete.js.erb文件;
$('#<%= dom_id(@idea)%>').html("What here? How can I toggle between the complete and incomplete links?");
我也尝试将link_to放在新的部分中,但这变得太复杂了(因为它们是子部分)并且也没有用。
我应该在我的complete.js.erb文件中尝试什么?
编辑:谢谢@Fer!我做了以下更改,但它还没有完全发挥作用。我将complete.js.erb更改为:
$("#toggle_completion_link").text("<%= @idea.completed? ? 'Incomplete' : 'Complete' %>")
我把想法改成了@idea,因为没有它我得到了一个'未定义的局部变量或方法'idea''错误。
同样在_idea.html.erb partial,在projects / idea.html.erb下,我改为:
<%= link_to (idea.completed? ? 'Incomplete' : 'Complete'), complete_project_idea_path(idea.project, idea), method: :patch, remote: true, id: 'toggle_completion_link' %>
但它还没有正常工作,虽然我确实得到了“完成200 ok”的消息。
Started PATCH "/projects/1/ideas/4/complete" for ...
Processing by IdeasController#complete as JS
Parameters: {"project_id"=>"1", "id"=>"4"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Project Load (0.2ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1 [["id", 1]]
Idea Load (0.2ms) SELECT "ideas".* FROM "ideas" WHERE "ideas"."project_id" = $1 AND "ideas"."id" = $2 ORDER BY priority ASC LIMIT 1 [["project_id", 1], ["id", 4]]
Rendered ideas/complete.js.erb (0.5ms)
Completed 200 OK in 9ms (Views: 3.3ms | ActiveRecord: 1.8ms)
答案 0 :(得分:1)
嗯,在您的情况下,您只需要更改链接文本,因为两个链接都指向相同的网址和方法。
我会在_idea.html.erb
<li id="<%= dom_id(idea) %>">
<%= idea.description %>
<%= link_to (idea.completed? ? 'Incomplete' : 'Complete'), complete_project_idea_path(idea.project, idea), method: :patch, remote: true, id: 'toggle_completion_link' %>
</li>
请注意最后链接的id
属性。
如果您要显示多个项目并且您遇到了ID问题,我会使用dom_id(idea)
作为链接的ID(或某些变体,例如dom_id(idea) + '_link'
),而不是li
1}}包含它。
然后,作为您的ajax请求的回答,在complete.js.erb
文件中:
$("#toggle_completion_link").text("<%= idea.completed? ? 'Incomplete' : 'Complete' %>")
您也可以替换整个内容,但我不明白这一点,因为您只需要切换链接文本。无论如何,对于教学法,你可以像下面一样渲染整个部分:
$("#<%= dom_id(idea) %>").replace("<%= escape_javascript(render 'idea', object: @idea %>")
您可能需要调整部分路径,因为您不知道它位于何处