未找到Rails简单表单关联

时间:2015-04-09 05:14:45

标签: ruby-on-rails ruby-on-rails-4 devise associations simple-form

我正在使用Simple Form和Invoicing gem,但是当我尝试渲染表单时,我在“Association:sender_id not found”中得到“InvoicingLedgerItems #new中的RuntimeError”。我想在sender_id字段中保存Users表(Devise gem)的主键(因为用户是发票的发件人)。我尝试在模型中使用foreign_key选项,但它似乎没有任何效果。这是我的代码,不使用foreign_key选项。

型号:

class InvoicingLedgerItem < ActiveRecord::Base
  acts_as_ledger_item

  belongs_to :user
  has_many :line_items, class_name: 'InvoicingLineItem', foreign_key: :ledger_item_id
  accepts_nested_attributes_for :line_items
end

class User < ActiveRecord::Base
  has_many :invoicing_ledger_items
end

查看:

<%= simple_form_for @invoicing_ledger_item do |f| %>
  <%= f.association :sender_id %>
  <%= f.button :submit %>
<% end %>

架构:

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.datetime "deleted_at"
  end

  create_table "invoicing_ledger_items", force: true do |t|
    t.integer  "sender_id"
    t.integer  "recipient_id"
    t.string   "type"
    t.datetime "issue_date"
    t.string   "currency",     limit: 3,                           null: false
    t.decimal  "total_amount",            precision: 20, scale: 4
    t.decimal  "tax_amount",              precision: 20, scale: 4
    t.string   "status",       limit: 20
    t.string   "identifier",   limit: 50
    t.string   "description"
    t.datetime "period_start"
    t.datetime "period_end"
    t.string   "uuid",         limit: 40
    t.datetime "due_date"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

2 个答案:

答案 0 :(得分:1)

您需要通过外键“sender_id”

与用户模型建立关系

<强>模型

class InvoicingLedgerItem < ActiveRecord::Base  
  acts_as_ledger_item  
  belongs_to :user, foreign_key: :sender_id  
  has_many :line_items, class_name: 'InvoicingLineItem', foreign_key: :ledger_item_id  
  accepts_nested_attributes_for :line_items  
end

需要将用户关联为隐藏字段

查看:

<%= simple_form_for @invoicing_ledger_item do |f| %>  
  <%= f.association :user, :as => :hidden, :input_html => { :value => curren_user.id } %>  
  <%= f.button :submit %>  
<% end %>

答案 1 :(得分:0)

您应首先在架构中使用user_id而不是sender_id。然后在alias_attribute :user_id, :sender_id模型中使用InvoicingLedgerItem,通过此辅助方法,您可以为此分配新名称字段名称。

如需更多参考,请访问http://api.rubyonrails.org/classes/Module.html