0

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

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

目前我有以下内容:

 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

4

1 回答 1

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

于 2012-06-23T13:03:34.277 回答