我的应用程序设置为用户拥有任务,而其他用户可以自愿完成这些任务。我的模型设置如下:
用户
class User < ActiveRecord::Base
has_many :participations, foreign_key: :participant_id
has_many :owned_tasks, class_name: "Task", foreign_key: :owner_id
end
参与(加入表格)
class Participation < ActiveRecord::Base
enum status: [:interested, :selected]
belongs_to :task
belongs_to :participant, class_name: "User"
end
任务
class Task < ActiveRecord::Base
enum status: [:open, :in_progress, :complete]
has_many :participations
has_many :participants, through: :participations, source: :participant
# Dynamically generates relations such as 'selected_participants'
Participation.statuses.keys.each do |status|
has_many "#{status}_participants".to_sym,
-> { where(participations: { status: status.to_sym }) },
through: :participations,
source: :participant
end
belongs_to :owner, class_name: "User"
end
我想做的只是让用户点击志愿者按钮,查看该特定任务的显示视图中的任务。
我可以在我的rails控制台中轻松完成此任务:
user = User.first
task = Task.first
user.owned_tasks << task
user_2 = User.find(2)
task.participants << user_2
我遇到的问题是试图找出如何设置必要的控制器代码以使其工作。我还不确定创建检查用户是否已参与任务is_participating?
的条件的方式/位置。它是否进入加入模式Participation
或Task
表?
我认为我对视图应该是什么样子有一个模糊的想法:
任务 - 显示视图
<% unless current_user == @task.owner %>
<div class="volunteer-form">
<% if current_user.is_participating? %>
<%= render 'cancel' %>
<% else %>
<%= render 'volunteer' %>
<% end %>
</div>
<% end %>
_volunteer.html.erb:
<%= form_for(current_user.participations.build(participant_id: current_user), remote: true) do |f| %>
<div><%= f.hidden_field :participant_id %></div>
<%= f.submit "Volunteer" %>
<% end %>
_cancel.html.erb:
<%= form_for(current_user.participations.find_by(participant_id: current_user), html: { method: :delete }, remote: true) do |f| %>
<%= f.submit "Cancel" %>
<% end %>
JS
// create.js.erb
$(".volunteer-form").html("<%= escape_javascript(render('tasks/volunteer')) %>");
// destroy.js.erb
$(".volunteer-form").html("<%= escape_javascript(render('tasks/cancel')) %>");
答案 0 :(得分:0)
从您的视图看起来is_participating?
属于User
模型,它可能应该是这些内容:
def is_participating?(task_id)
participations.where(task_id: task_id).exists?
end
至于控制器代码,您可能需要这些内容:
class ParticipationsController
# Note I assume you have access to current_user here
def create
participation = current_user.participations.create(participation_params)
respond_to do |format|
format.js
end
end
def destroy
participation = current_user.participations.find(params[:id])
participation.destroy
respond_to do |format|
format.js
end
end
protected
def participation_params
params.require(:participation).permit :task_id
end
end
在 _volunteer.html.erb 上(请注意,您现在必须将task
传递给部分内容):
<%= form_for(current_user.participations.build, remote: true) do |f| %>
<%= f.hidden_field :task_id, value: task.id %>
<%= f.submit "Volunteer" %>
<% end %>