繁体   English   中英

Ruby on Rails-将动态表单下拉菜单值插入表

[英]Ruby on rails - insert dynamic form drop down menu values to table

我试图将下拉菜单值插入到名为units的表中,并且该下拉值来自另一个名为properties的模型。

这是单元的架构。

create_table "units", :force => true do |t|
    t.string   "number"
    t.decimal  "monthly_rent"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "property_id"
  end

在我的view / units / new.html.erb上我有这个。

<% form_for @unit do |f| %>
<%= f.error_messages %>
<p>
    <%= f.label :property_id %>
    <br/>
    <%= select (:unit, :property_id, Property.all.collect  {|property| [property.name,property.id,]}) %>
</p>
<p>
    <%= f.label :number %>
    <br/>
    <%= f.text_field :number %>
</p>
<p>
    <%= f.label :monthly_rent %>
    <br/>
    <%= f.text_field :monthly_rent %>
</p>
<p>
    <%= f.submit "Submit" %>
</p>
<% end %>

这是我的控制器方法

def create
    @unit = Unit.new(params[:unit])
 # @unit.property_id = 1

    if @unit.save
      flash[:notice] = "Successfully created unit."
      redirect_to @unit
    else
      render :action => 'new'
    end
  end

只有numbermonthy_rent插入到表中,但property_id没有出现。 可以帮我一下吗? 谢谢

我从您看到的内容中可能看到的问题是您选择的帮助程序中的错误逗号。 尝试像这样重写它(也使用form helper方法):

<%= f.select :property_id, Property.all.collect {|property| [ property.name, property.id ] } %>

是的,create params的输出到您的日志将极大地帮助您。

我想通了,对不起,这是我的错。 它不工作,因为, property_id不添加到attr_accessible ,一旦我补充说,它的工作。 但我仍然不知道确切的问题。

class Unit < ActiveRecord::Base
  belongs_to :property
  attr_accessible :number, :monthly_rent, :property_id
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM