我需要創建用戶團隊。用戶屬於一個團隊(只有一個團隊),一個團隊有許多用戶。我無法弄清楚如何讓用戶能夠創建,加入和離開團隊。下面是我到目前爲止,但我敢肯定,我正在做一些可怕的事情(和「新的」錯誤)。用戶團隊Rails應用程序
用戶模型:
belongs_to :teams, dependent: :destroy
def team_member?(team)
team_relationships.find_by_team_id(team.id)
end
def join!(team)
team_relationships.create!(team_id: team.id)
end
def unjoin!(team)
team_relationships.find_by_team_id(team.id).destroy
end
團隊模式
has_many :users, through: :team_relationships, dependent: :destroy
attr_accessible :team_name, :team_id
validates :user_id, presence: true
validates :team_name, presence: true, length: { maximum: 140 }
default_scope order: 'teams.created_at DESC'
team_relationship模型
attr_accessible :team_id
belongs_to :team
belongs_to :user
validates :team_id, presence: true
路線:
resources :teams do
member do
get 'join'
get 'leave'
end
end
teams_controller:
def join
@team = Team.find params[:team_id]
current_user.update_attribute(:team_id, @team.id)
redirect_to @user
end
def leave
@team = Team.find params[:id]
current_user.update_attribute(:team_id, nil)
redirect_to @user
end
_join_team.html.erb
<%= form_for(current_user.team_relationships.build(team_id: @team_id),
remote: true) do |f| %>
<div><%= f.hidden_field :team_id %></div>
<%= f.submit "Join", class: "btn btn-large btn-primary" %>
<% end %>
_unjoin_team.html.erb
<%= form_for(current_user.team_relationships.find_by_team_id(@team_id),
html: { method: :delete }) do |f| %>
<%= f.submit "Leave Team", class: "btn btn-large" %>
<% end %>
如果你不能告訴我在努力適應一些什麼在Hartl的教程爲此目的。我究竟做錯了什麼?
我相信我已經弄清了模型,但現在我不確定如何讓用戶創建團隊,摧毀團隊,加入團隊或離開團隊。我需要在模型,控制器和視圖中做什麼才能實現?
您可以發佈爲用戶模型的代碼? – depa
它在頂部只是沒有正確縮進;) –
@SteaveQ是team_relationships?一箇中間誹謗模式,或者你想參考團隊? – PriteshJ