【问题标题】:Rails 3 complex form with nested attributes具有嵌套属性的 Rails 3 复杂表单
【发布时间】:2013-04-23 16:04:01
【问题描述】:

我有一个单一的表格,其中有车辆详细信息、投诉详细信息和用户详细信息。车辆有_many 投诉和用户有_many 投诉。它是一个嵌套的_attribute 表格,但由于某种原因,我觉得该关联是错误的,我有点困惑该表格应该如何使用是或者应该是投诉has_one 车辆和投诉has_one 用户? 我在创建投诉时创建新用户和新车辆。此表单没有任何身份验证..

车辆.rb

 class Vehicle < ActiveRecord::Base
   attr_accessible :number, :vehicle_types , :complaints_attributes
   has_many :complaints
   accepts_nested_attributes_for :complaints
 end

用户.rb

 class User < ActiveRecord::Base
  attr_accessible :address, :email_id, :mobile , :complaints_attributes
  has_many :complaints
  accepts_nested_attributes_for :complaints
 end

投诉.rb

class Complaint < ActiveRecord::Base
  attr_accessible  :indecent_behaviour, :occurence_date_time, :other_complaints,      :place_occurence
  belongs_to :user
  belongs_to :vehicle 
end

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    我不明白为什么用户和车辆会有嵌套的投诉。您可能不会在创建新用户和新车辆的同时创建投诉。你是吗?

    假设一个用户被制造出来,一辆汽车被制造出来,然后一个用户对一辆汽车提出投诉,这时就提出了一个投诉。按时间顺序晚于创建用户或车辆的时间。

    所以,也许取出嵌套属性。相反,您可以使用隐藏字段并将车辆 ID 作为参数传递,或者您可以使用嵌套资源路径来获取车辆 ID。通过投诉的 current_user 的 has_many 关联创建投诉:

    new_complaint_path( vehicle_id: @vehicle.id )
    

    在投诉控制器中

    def new
      @complaint = current_user.complaints.build
      @complaint[:vehicle_id] = params[:vehicle_id]
    end
    

    【讨论】:

    • 感谢您的回复..是的,我在创建投诉时创建了新用户和新车..此表单没有任何身份验证..
    猜你喜欢
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多