[英]has_and_belongs_to_many relationship in ruby on rails
我正在嘗試為使用紅寶石的網球教練制作一個網站。 我對此完全陌生,並且在某些術語方面苦苦掙扎。 該網站有一個登錄系統,用戶可以登錄,然后注冊網球教練創建的不同事件。 因此,基本上,用戶可以參加許多活動,並且這些活動可以有許多用戶參加。 我在用戶表和事件表之間建立了has_and_belongs_to_many
關系,代碼如下:
這是我的遷移:
class CreateEventsUsers < ActiveRecord::Migration
def change
create_table :events_users, :id => false do |t|
t.integer :event_id
t.integer :user_id
end
add_index :events_users, :event_id
add_index :events_users, :user_id
add_index :events_users, [:event_id, :user_id]
end
def self.down
drop_table :events_users
end
end
這是我的模型:
class User < ActiveRecord::Base
has_and_belongs_to_many :events
end
class Event < ActiveRecord::Base
has_and_belongs_to_many :users
end
這是我的活動表格:
<li>
<%= link_to event.title, event %>
| <%= link_to "delete", event, method: :delete %>
| *insert sign up here*
</li>
基本上,我的問題是,我將如何創建一個表單和一個控制器來讓已登錄的用戶注冊數據庫中的一個事件? 我已經堅持了好幾天。 任何幫助將不勝感激。
如果您還沒有發現它,那么如果您查看Ryan Bates的railscasts,就可以享受真正的享受。 這是一個關於如何使用具有HABTM關聯的形式的復選框的教程-實際上,他建議,您應該考慮通過關系而不是HABTM轉向has_many。
無論如何,它至少應該使您了解如何使其在應用程序中運行。 http://railscasts.com/episodes/17-habtm-checkboxes-revised 。 該劇集可能需要會員資格,但是,每月9美元的bux對於您所獲得的來說是完全合理的。
對於可伸縮性問題,我建議使用has_many而不是has_and_belongs_to,這是一種建議的做法。 滿足您的要求,我做了類似的事情,但用戶跟隨其他用戶,並嘗試采用其中的一些以滿足您的要求。
class Event < ActiveRecord::Base
has_many : Relationship
has_many : users, :through => :Relationships
end
class User < ActiveRecord::Base
has_many :Relationship
has_many :events, :through => :Relationships
//define other methods//
def follow!(event_id)
relationships.create!(event_id: event.id)
end
end
class Relationship < ActiveRecord::Base
attr_accessible :event_id
belongs_to :events
belongs_to :users
end
您需要像這樣創建關系遷移
class CreateRelationships < ActiveRecord::Migration
def change
create_table :relationships do |t|
t.integer :user_id
t.integer :event_id
t.timestamps
end
add_index :relationships, :user_id
add_index :relationships, :event_id
add_index :relationships, [:user_id, :event_id], unique: true
end
end
您可以嘗試像這樣在事件頁面視圖上添加按鈕。
<%= form_for(current_user.relationships.build(evnt_id: @user.id)) do |f| %>
<div><%= f.hidden_field :event_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
關系控制器可以是這樣的。
class RelationshipsController < ApplicationController
def create
@user = User.find(params[:relationship][:event_id])
current_user.follow!(@user)
respond_to do |format|
format.html { redirect_to @user }
end
end
end
本教程對我開發應用程序以使用戶關注其他用戶非常有幫助。 希望它也會對您有幫助。 祝好運 !! http://ruby.railstutorial.org/chapters/following-users#top
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.