Ruby on Rails - 获取表单输入并将其插入数据库的正确方法

时间:2012-04-23 18:37:46

标签: ruby-on-rails ruby haml

我有这样的表格:

= form_for([:mobile,@disclosure], :html => {:id => "disclosure-form", :remote => true}) do |f|
      %p
        =f.label :display_as, (t :select_disclosure_type)
        =f.select :display_as, options_from_collection_for_select(Disclosure.basics, :display_as,
          :name, f.object.display_as)
      %p
        =f.label :notes, (t :notes)
        =f.text_area :notes, :class => "#{validation_rules(:free_disclosure_notes)}", :rows => 5 , :id => "disclosure_notes_entry"
        = buttonset({:submit_label => (t "buttons.influencers.disclosures.create"),:submit_css_class => "call-to-action",
          :cancel_url => "#",:direction => :left_to_right})

到目前为止我有这个控制器:

  def create
    Rails.logger.debug "-"*100
    Rails.logger.debug session.inspect
    Rails.logger.debug "-"*100

    provider = nil

    @disclosure = params[:disclosure-form].blank?
    resource = build_resource({})

    begin
      if disclosure.nil?
        print "hello 1"
      else
          print "hello 2"
      end

    rescue Exception => ex
      Rails.logger.debug ex

    end

    respond_to do |format|
      format.html{}

    end
  end

但我不确定如何填充@disclosures对象以便我可以将其插入数据库?

如何从表单中获取正确的数据并将其添加到数据库?

谢谢!

1 个答案:

答案 0 :(得分:2)

您的表单数据应该是params[:disclosure]哈希值。因此,在您的create操作中,您可以执行以下操作:

def create
  @disclosure = Disclosure.new(params[:disclosure])

  if @disclosure.save
    # redirect to show or something else
  else
    # render 'new' for with validation errors
  end
end

这应该将您的对象保存在DB中。如果没有验证错误。

我不确定这句话的作用:@disclosure = params[:disclosure-form].blank?