ruby on rails has_many通过关系

时间:2012-06-08 21:51:15

标签: ruby-on-rails database-design rails-activerecord has-many-through

你好我的应用程序的has_many关系有点麻烦,并希望找到一些帮助。所以我有用户&讲座。讲座由一个用户创建,然后其他用户可以“加入”已创建的讲座。用户拥有他们自己创建的讲座的简档摘要&还有朋友创建的讲座提要。然而,这个问题不是关于创建讲座而是“加入”已经创建的讲座。我创建了一个“讲座关系”模型&控制器处理演讲与演讲之间的这种关系;已加入的用户(我称之为“活动”)。然后用户也必须“退出”讲座(通过单击“退出”或导航到其中一个标题导航链接)。如果有人能和我一起完成其中的一些工作,我感激不尽......

我有: Users.rb模型 Lectures.rb模型 Users_controller Lectures_controller

然后是以下模型

lecturerelationship.rb

class lecturerelationship < ActiveRecord::Base
  attr_accessible :active_id, :joinedlecture_id

  belongs_to :active, :class_name => "User"
  belongs_to :joinedlecture, :class_name => "Lecture"

  validates :active_id, :presence => true
  validates :joinedlecture_id, :presence => true

end

lecturerelationships_controller.rb

class LecturerelationshipsController < ApplicationController
  before_filter :signed_in_user

  def create
   @lecture = Lecture.find(params[:lecturerelationship][:joinedlecture_id])
   current_user.join!(@lecture)
   redirect_to @lecture
  end

 def destroy
  @lecture = Lecturerelationship.find(params[:id]).joinedlecture
  current_user.exit!(@user)
  redirect_to @user
 end

end

已创建的讲座(由朋友创建)显示在以下文件中的用户Feed

_activity_item.html.erb

<li id="<%= activity_item.id %>">
  <%= link_to gravatar_for(activity_item.user, :size => 200), activity_item.user %><br   clear="all">
  <%= render :partial => 'shared/join', :locals => {:activity_item => activity_item} %>
  <span class="title"><%= link_to activity_item.title, lecture_url(activity_item)  %></span><br clear="all">
  <span class="user">
   Joined by <%= link_to activity_item.user.name, activity_item.user %>
  </span><br clear="all">
  <span class="timestamp">
   <%= time_ago_in_words(activity_item.created_at) %> ago.
  </span>
  <% if current_user?(activity_item.user) %>
    <%= link_to "delete", activity_item, :method => :delete,
                                     :confirm => "Are you sure?",
                                     :title => activity_item.content %>
  <% end %>
</li>

然后你看到我链接到上面的'共享/加入'部分,可以在下面的文件中看到

_join.html.erb

<%= form_for(current_user.lecturerelationships.build(:joinedlecture_id =>  activity_item.id)) do |f| %>
  <div>
   <%= f.hidden_field :joinedlecture_id %>
  </div>
  <%= f.submit "Join", :class => "btn btn-large btn-info" %>
<% end %>

可能需要更多文件:

配置/ routes.rb中

SampleApp::Application.routes.draw do
  resources :users do
    member do
    get :following, :followers, :joined_lectures
  end
end

resources :sessions, :only => [:new, :create, :destroy]
resources :lectures, :only  => [:create, :destroy, :show]
resources :relationships, :only => [:create, :destroy] #for users following each other
resources :lecturerelationships, :only => [:create, :destroy] #users joining existing lectures

所以会发生的事情是我的activity_feed讲话在底部有一个加入按钮选项...这应该创建一个“活跃”&amp;的讲座关系。 “joinlecture”(显然应该来自用户和讲座课程。但是当我点击加入按钮时我得到的错误如下:

ActiveRecord::StatementInvalid in LecturerelationshipsController#create

SQLite3::ConstraintException: constraint failed: INSERT INTO "lecturerelationships"     ("active_id", "created_at", "joinedlecture_id", "updated_at") VALUES (?, ?, ?, ?)

此外,我已经包含了我的用户模型(似乎错误是指它) user.rb

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation
  has_secure_password
  has_many :lectures, :dependent => :destroy


  has_many :lecturerelationships, :foreign_key => "active_id", :dependent => :destroy
  has_many :joined_lectures, :through => :lecturerelationships, :source =>    :joinedlecture

  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token

  validates :name, :presence => true, :length => { :maximum => 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, :presence => true,
        :format => { :with => VALID_EMAIL_REGEX },
        :uniqueness => { :case_sensitive => false }
  validates :password, :presence => true, :length => { :minimum => 6 }
  validates :password_confirmation, :presence => true

  def activity
    # This feed is for "My Activity" - basically lectures i've started
    Lecture.where("user_id = ?", id)
  end

  def friendactivity
     Lecture.from_users_followed_by(self)
  end

  # lECTURE TO USER (JOINING) RELATIONSHIPS
  def joined?(selected_lecture)
    lecturerelationships.find_by_joinedlecture_id(selected_lecture.id)
  end

  def join!(selected_lecture)
    lecturerelationships.create!(:joinedlecture_id => selected_lecture.id)
  end

  def exit!(selected_lecture)
   lecturerelationships.find_by_joinedlecture_id(selected_lecture.id).destroy
  end


end

感谢您提供任何帮助 - 我会在这里待一段时间,所以我非常感谢能够有时间与我一起解决问题的人...

2 个答案:

答案 0 :(得分:2)

我将从以下模型开始,使用Enrollment作为成员资格表 类命名对此至关重要。

class User < ActiveRecord::Base
  has_many :enrollments
  has_many :users, :through => :enrollments
end

class Lecture < ActiveRecord::Base
  has_many enrollments
  has_many users, :through => :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :user
  belongs_to :lecture
end

rails的主要技巧是使用正确的名称并遵循约定,让框架为您完成大部分工作。走开路径,错误可能是无穷无尽的,代码很快就会变得混乱:)

答案 1 :(得分:1)

您的_join.html.erb似乎使用build来构建新的lecturerelationships关联,然后join!来电使用create来制作另一个database is locked: commit transaction宾语。我的猜测是第二个调用中断了第一个调用启动的事务,这就是你得到{{1}}错误的原因。

我认为将这类代码排除在您的观点之外是一种良好的做法。