使用外键关联模型

时间:2016-02-26 23:06:10

标签: mysql ruby-on-rails-4 has-many-through

我的目标是设置用户创建Grants作为资助者的设置,然后将其他用户与资助作为资源进行匹配。我一直在为模型设置提供一些选项,例如:

class Grant < ActiveRecord::Base
 belongs_to :funder, class_name:"User", foreign_key:"funder_id"
 has_many :matches
 has_many :researchers, class_name: "User", source: :user, through: :matches


class User < ActiveRecord::Base
has_many :matches
has_many :grants, through: :matches


class Match < ActiveRecord::Base
 belongs_to :user
 belongs_to :grant


Or ——————————————————————



 class Grant < ActiveRecord::Base
  has_many :funder_matches, :foreign_key => :researcher_id, :class_name => "Match"
  has_many :researcher_matches, :foreign_key => :funder_id, :class_name => "Match"
  has_many :researchers, through: :researcher_matches
  has_many :funders, through: :funder_matches



class Match < ActiveRecord::Base
  belongs_to :grant
  belongs_to :user
  belongs_to :funder, :class_name => "User"
  belongs_to :researcher, :class_name => "User"

class User < ActiveRecord::Base
  has_many :matches
  has_many :grants, through: :matches

然后在此期间,管理员通过访问用户配置文件并传入user_id来创建授权。

在授权模型中,我有:

def create_grant_with_associations(current_user)
    current_user.grants << self
    self.funder = current_user
    self.save
 end

我也在Grants表和我有的授权控制器上有funder_id

def create
    @grant = @@user.grants.build(grant_params)
      if @grant.save
        @grant.create_grant_with_associations(@@user)
        flash[:info] = "The grant was successfully created" 
        redirect_to @grant
      else
        render 'new'
    end
  end

然后最后我有一个集合选择允许管理员选择授权并与用户匹配。

<h4>Match a grant:</h4>
  <%= form_for @user, :html => { :class => 'form-horizontal', :multipart => true }  do |f| %> 
      <div class="field "> 
        <%= f.label :grants, "Select Grant" %> 
        <%= f.collection_select(:grant_ids, Grant.all, :id, :name,{:include_blank => 'Show No Grants Matched'},  :multiple => true) %> 
      </div>   
  <%= f.submit "Create Match", class: "btn btn-primary"%>
  <% end %>

我现在遇到的问题是,当我使用该集合时,它会覆盖资助者协会。我是在正确的轨道上吗?

0 个答案:

没有答案