在作业,应用程序和用户之间创建关联的正确方法

时间:2012-06-23 11:44:53

标签: ruby-on-rails ruby-on-rails-3.1

我正在创建一个允许用户创建和申请工作的应用。

我遇到的问题是让我的三个模型之间的关联正确。

目前我有以下内容:

 class App < ActiveRecord::Base
    belongs_to :job
    belongs_to :user
 end 

 class Job < ActiveRecord::Base
    belongs_to :user, :dependent => :destroy
    has_many :apps, :through => :users
 end

 class User < ActiveRecord::Base
    has_many :jobs
    has_many :apps, :through => :jobs
 end

在我的应用数据库表中,我有两个额外的user_id和job_id列,以便可以在那里正确地建立关联。

我也不确定如何创建一个表单来说一个新的应用程序。目前我使用了以下内容,但因为我没有应用程序作为用户的嵌套资源,我不确定这是否是导致问题的原因:

 class AppsController < ApplicationController

 def new
   @user = current_user
   @app = @user.apps.build
 end

def create
  @user = current_user
  @app = @user.apps.create(params[:app])
  if @app.save
    redirect_to user_path
  else
    render new_app_path
  end
end

<%= form_for [@app] do |f| %>

<div class = "field">
    <%= f.label :name %>
    <%= f.text_field :name %>
</div>

<div class = "field">
    <%= f.label :cover_letter %>
    <%= f.text_field :cover_letter %>
</div>

<div class = "field">
    <%= f.label :cv %>
    <%= f.text_field :cv %>
</div>

<%= f.submit "Submit" %>

<% end %>

如果有人可以提供他们如何为这个应用程序设置关联以及如何确保相关表单与此设置一起工作的示例,那就太棒了。

提前感谢您的帮助!

我还将我的应用推送到Github以防万一:Github Link

1 个答案:

答案 0 :(得分:1)

我认为用户和作业之间会存在多对多的关系。应用程序可以充当连接表(作为jobs_users)。

所以型号......

class App < ActiveRecord::Base 
    belongs_to :job
    belongs_to :user
end

class Job < ActiveRecord::Base
     has_many :users
     has_many :apps, :through => :apps
end

class User < ActiveRecord::Base
     has_many :jobs,:dependent => :destroy
     has_many :apps, :through => :apps
end

对于嵌套表格,请仔细阅读 http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast