Rails mongoid, simple_form, accepts_nested_attributes_for, 崩溃了。

calebx · 2012年05月11日 · 最后由 aNdReW_Qx 回复于 2012年05月11日 · 3809 次阅读

受不了啦,给我一个理由阿: M 如下:

class Trip
  include Mongoid::Document
  include Mongoid::Timestamps
  field :title, :type => String
  has_many :steps, :dependent => :destroy
  accepts_nested_attributes_for :steps
end

class Step
  include Mongoid::Document
  include Mongoid::Timestamps
  field :content, :type => String
  validates_presence_of :content
  belongs_to :trip
end

C 如下:

class TripsController < ApplicationController
  def new
    @trip = Trip.new
    respond_with(@trip) do |format|
      format.html # new.html.erb
      format.json { render json: trip }
    end
  end
  ......

V 如下:(haml)

= simple_form_for @trip do |f|
  = f.input :title
  = f.simple_fields_for @trip.steps.build do |sf|
    = sf.input :content
  = f.submit 'Save'

不知为何,form 页面看上去很正常:

<input class="string required" id="trip_step_content" name="trip[step][content]" required="required" size="50" type="text">

但 post 上去,params 就变成了:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"GgiUuDS8YcBmFhkt5jYGNXGBho/eVZuVQhB4K1S0KEo=", "trip"=>{"title"=>"111", "step"=>{"content"=>"111"}}, "commit"=>"Save"}

而 mongoid 要求的 step 参数却是:steps_attributes; 但凡能 stackoverflow 到的,都不会这样阿。 求教:mongoid 的 accepts_nested_attributes_for 应该如何写 viewer 阿; simple_field_for 如何写?

{ trip: { title: "111", steps_attributes: [{ content: "111" }] }

#2 楼 @mimosa 对阿;对阿; 可是如何让 field_for 出来的东东,自动可以再 controller 里头解析成{ trip: { title: "111", steps_attributes: [{ content: "111" }] }呢?在 viewer 和 controller 里面需要添加什么呢?

trip[title]
trip[steps_attributes][][content]

@calebx

#4 楼 @mimosa 这样做固然可以,但这样子是不是很勉强阿; 相当的勉强; 有发现:是再 model 上又 expose 的缘故,我把在 model 上添加了 expose 去掉; 就可以解析成为"trip"=>{"title"=>"123", "steps_attributes"=>{"0"=>{"content"=>"123"』 但是解析了之后仍然没办法让 mongoid 保存。 见鬼来。

new action 方法中加上这个:3.times { @trip.steps.build }

non-sense; 发现问题了:mongoid 的 autosave: true, 再 belongs_to association 中已经无效; 需在在 controller 中写:@trip.save; @trip.steps.each{|s| s.save}; 才有效; 气死我了!

#7 楼 @calebx

f.simple_field_for :steps , Step.new

这样即可

需要 登录 后方可回复, 如果你还没有账号请 注册新账号