【问题标题】:Populate foreign key in belongs_to association在 belongs_to 关联中填充外键
【发布时间】:2014-02-16 05:08:01
【问题描述】:

基本上,我只需要在我的业务表中正确分配一个 template_id 字段,这样如果我执行 Business.first.template 它将返回当前为该业务分配的模板的结果。在我得到的那一刻,我只是得到'nil'

在我的项目中,业务属于模板(我相信这会将主键放在模板表中,将外键放在业务表中)。

class Business < ActiveRecord::Base
belongs_to :template

class Template < ActiveRecord::Base
has_many :businesses

当用户为“新业务”填写表单时,他们会选择他们希望使用的模板。模板表已经填满了 3 个模板,template_id, 0, 1, 2(所以我真的不知道是否需要“创建”任何东西)。用户只能通过表单选择 3 个模板(单选按钮)之一。

提交表单并创建业务时,当前未创建业务与模板之间的链接。我的业务类中没有关于模板创建的任何内容,因为我无法确定需要创建什么,模板记录已经存在于模板表中并且是静态的。

Business Controller
  def new
    @business = current_user.businesses.build
    @business.addresses.build
  end

  # POST /businesses
  def create
    @business = Business.new(business_params)
    @business.users << current_user
    if @business.save
      redirect_to @business, notice: 'Business was successfully created.'
    else
      render action: 'new'
    end
  end

  def business_params
    params.require(:business).permit(:name, :email, :template_id, addresses_attributes [:number, :street, :suburb, :state, :country], template_attributes: [:name])

我不确定我是应该自己分配 template_id 还是使用 'build_template' 做某事

架构

  create_table "businesses", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "name"
    t.string   "description"
    t.string   "sub_heading"
    t.string   "email"
    t.integer  "template_id"
  end

  create_table "templates", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "name"
    t.integer  "cost"
  end

我不确定我是否应该直接从用户提交的表单中将值分配为 0、1 或 2 到业务表中的 template_id,或者我是否应该像处理地址表一样允许嵌套属性.

感谢任何帮助。 谢谢

【问题讨论】:

    标签: ruby-on-rails foreign-keys associations belongs-to


    【解决方案1】:

    不过,模板 id 的外键就可以了。它将Business 的实例与Template 的实例联系起来。

    您不是在创建模板,而是已经从创建的模板列表中选择了一个。您可以访问一个企业的模板应该像Business.find(id).template 一样简单,其中 Id 是您想要了解的企业的 ID。

    【讨论】:

    • 谢谢!这就是我所需要的。我已经习惯了编写 SQL,有时似乎很难用活动记录来做这么简单的事情。
    猜你喜欢
    • 2011-03-08
    • 2014-05-13
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多