同时创建两个对象

Jse*_*seb 1 ruby geocoding ruby-on-rails ruby-on-rails-3

我试图同时创建两个对象,但由于某种原因,我的第二个对象的字段是空白的.

模型是:

Users: id, name, last, email, password ...
Locations: address, longitude, latitude.
Run Code Online (Sandbox Code Playgroud)

关系如此:

User has_many location
Location belongs_to users
Run Code Online (Sandbox Code Playgroud)

事件控制器创建方法:

def create
    @event = current_users.events.build(params[:event])
    @location = @event.locations.build(params[:location])
    @location.longitude = params[:longitude]
    @location.latitude = params[:latitude]
    respond_to do |format|
      if @location.save
        @location.longitude = params[:longitude]
        @location.latitude = params[:latitude]
        if @location.save
          if @event.save
            format.html { redirect_to @event, notice: 'Event was successfully created.' }
            format.json { render json: @event, status: :created, location: @event }
          else
            format.html { render action: "new" }
            format.json { render json: @event.errors, status: :unprocessable_entity }
          end
        end
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

形式:

  <%= f.hidden_field :latitude %>
  <%= f.hidden_field :longitude %>
Run Code Online (Sandbox Code Playgroud)

但是,当我创建我的位置,我得到空白longitudelatitude,我event_id是虽然填满.是否有更好的方法同时创建两个对象?

Yve*_*enn 5

您的两个字段是使用表单生成器生成的f.我怀疑他们正在form_for打电话.这样做的结果是字段名称将嵌套在模型的命名空间中.这意味着params[<model name>][:longitude]并且params[<model name>][:latitude]应该具有字段的内容.

您可以检查控制台以查看rails接收的参数.或者,您可以将params哈希打印到控制台以检查其内容:( p params在您的操作中的某个位置).

因此,为了使一切正常,您需要访问正确的参数.(有点像params[:location][:longitude])