rails - form_for - 如何让我的'Property'表单更新'Ticket'模型?

时间:2013-05-03 09:37:47

标签: ruby-on-rails ruby-on-rails-3.2 form-for

我有3个表 - OwnerofPropertyPropertyTicket。我想使用form_for制作一个表格来代表物业预订;我可以创建一个表单来从Property检索数据,其中提交按钮将数据保存在Ticket表中吗?我在问,因为我不知道这是否可能或如何实现。

注意:我只创建了关系: OwnerofProperty一对多Property

Property一对一Ticket

我需要这个表单只是为了让用户能够看到可用的属性并且只能预订一个,如何制作这个表单?

三种模型的Schema.rb:

create_table "owners", :force => true do |t|
    t.string   "f_name"
    t.string   "l_name"
    t.string   "address"
    t.string   "tel_no"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "properties", :force => true do |t|
    t.string   "p_street"
    t.string   "p_city"
    t.string   "postcode"
    t.string   "property_type"
    t.integer  "rooms"
    t.integer  "rent"
    t.integer  "owner_id"
    t.datetime "created_at",    :null => false
    t.datetime "updated_at",    :null => false
  end

  add_index "properties", ["owner_id"], :name => "index_properties_on_owner_id"

  create_table "tickets", :force => true do |t|
    t.string   "city"
    t.string   "street"
    t.string   "ticket_type"
    t.integer  "rooms"
    t.integer  "rent"
    t.integer  "property_id"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  add_index "tickets", ["property_id"], :name => "index_tickets_on_property_id"

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。

让我们看看ticket_controller.rb

def new
  @property = Property.find 20  #20 is property id
  @properties = Property.all
  #@ticket = Ticket.new
end

现在位于view(您要在其中创建表单):

<%= form_for @ticket do |f| %>
<%= f.select :property_id, @properties.collect {|p| [ p.name, p.id ] }%> <!-- just an example, Ticket model has a field named "property_id" -->
<%= f.submit %>
<%= end %>

此表单提交create ticket_controller行动。您可以将所有数据作为params并将其保存到表格中。

def create
@ticket = Ticket.new(params[:ticket])
@ticket.save
  respond_to do |format|
    format.html{redirect_to( your_desired_path)}
  end
end