如何设置/限制轨道形式的输入以匹配另一个模型表?

时间:2018-04-02 12:07:53

标签: ruby-on-rails ruby

我对编程很陌生,并且无法找到任何资源来帮助我解决这个问题。我创建了两个支架帐户 Cashbooks 。我希望用户能够添加一个帐户(参数为account_name),然后将其设置为Cashbook帐户输入的参数。理想情况下,在添加Cashbook交易时,我希望用户看到一个下拉列表,其中包含已创建的帐户的所有account_names。

Cashbook Model

class Cashbook < ActiveRecord::Base
    belongs_to :account, foreign_key: :account_name
end

Cashbook Controller

def new
   @cashbook = Cashbook.new
   @cashbook.account(account_params[:account_name])
  end

  def create
    @cashbook = Cashbook.new(cashbook_params)
      @cashbook.account(account_params[:account_name])

def cashbook_params
      params.require(:cashbook).permit(:date, :description, :account, :kind, :amount, :balance, :name)
      params.require(:account).permit(:account_name)
    end

Cashbook DB

class CreateAccounts < ActiveRecord::Migration
  def change
    create_table :accounts do |t|
      t.string :account_name
      t.boolean :operating_expense
      t.boolean :cost_of_sales
      t.boolean :sales
      t.boolean :other_income
      t.boolean :non_current_liability
      t.boolean :non_current_asset
      t.boolean :current_asset
      t.boolean :current_liability
      t.boolean :equity
      t.integer :account_number

      t.timestamps null: false
    end
  end
end

帐户模型

class Account < ActiveRecord::Base
    has_many :cashbook, foreign_key: :account_name
end

帐户控制器

def new
    @account = Account.new
  end


  def edit
  end

  def create
    @account = Account.new(account_params)
  end

def account_params
      params.require(:account).permit(:account_name, :operating_expense, :cost_of_sales, :sales, :other_income, :non_current_liability, :non_current_asset, :current_asset, :current_liability, :equity, :account_number)
    end

Cashbook db

class CreateCashbooks < ActiveRecord::Migration
  def change
    create_table :cashbooks do |t|
      t.date :date
      t.string :description
      t.boolean :account
      t.string :kind
      t.integer :amount

      t.timestamps null: false
    end
  end
end

1 个答案:

答案 0 :(得分:0)

您可以使用collection_select表单助手。

在您的情况下,它可能看起来像

<%= collection_select(:cashbook, :account_name, Account.all, :account_name, :account_name) %>

虽然您还应考虑使用id列根据Rails Associations Guide关联模型。如果您更改模型以使用id s作为外键,则无需在has_manybelongs_to语句中明确指定外键,您仍然可以创建选择显示帐户名称的框:

<%= collection_select(:cashbook, :account_id, Account.all, :id, :account_name) %>