Rails 4.0记录不保存

时间:2014-06-02 19:19:47

标签: ruby-on-rails nested

我有一个拥有许多链接的商机模型。 Links是Opportunity的嵌套资源。在我的views / opportunities / show.html.erb页面上,我显示了属于该商机的所有链接,并且我也呈现了一个“新链接”表单。这个表格直到最近才运作良好,我不知道为什么。当我填写“新链接”表单并单击“添加”时,记录不会保存。有人可以帮我这个吗?

以下是我的观点/机会/ show.html.erb页面:

  <%= render @opportunity %>
  <form>
      <fieldset>
        <legend>Links</legend>
    <div id="links">
      <%= render @opportunity.links %>
    </div>
    <%= render :file => 'links/new' %>

   </fieldset>
 </form>

以下是我的观点/链接/新页面:

   <%= form_for ([@opportunity, @opportunity.links.new]) do |f| %>


        <div class="field">
            <%= f.label "Description:" %> <br />
            <%= f.text_field :description %> 
        </div>
        <div class="field">
            <%= f.label "URL:" %> <br />
            <%= f.text_field :link_url %> 
        </div>
        <div class="actions">
            <%= f.submit 'Add' %> 
        </div>

    <% end %>

这是我的创建链接控制器:

def create

  @opportunity = Opportunity.find(params[:opportunity_id])
  @link = @opportunity.links.new(link_params)
    if @link.save
      redirect_to @opportunity, notice: 'link has been added'
    else
      redirect_to @opportunity, alert: 'Unable to add link'
    end
  end

这是我的链接模型:

 class Link < ActiveRecord::Base

belongs_to :opportunity

 end

这是我的机会模型:

class Opportunity < ActiveRecord::Base

has_many :links
end

以下是我的控制台中的代码:

Started GET "/opportunities/7?utf8=%E2%9C%93&authenticity_token=ZLgPz98w2MjTChzzDXJ8EcqNmYNtBUG5DSYcp1CXReU%3D&link%5Bdescription%5D=testlink&link%5Blink_url%5D=testlink&commit=Add" for 127.0.0.1 at 2014-06-02 15:19:06 -0400
Processing by OpportunitiesController#show as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZLgPz98w2MjTChzzDXJ8EcqNmYNtBUG5DSYcp1CXReU=", "link"=>{"description"=>"testlink", "link_url"=>"testlink"}, "commit"=>"Add", "id"=>"7"}
  Opportunity Load (0.2ms)  SELECT  "opportunities".* FROM "opportunities"  WHERE "opportunities"."id" = ? LIMIT 1  [["id", 7]]
  Rendered opportunities/_opportunity.html.erb (2.0ms)
  Link Load (0.1ms)  SELECT "links".* FROM "links"  WHERE "links"."opportunity_id" = ?  [["opportunity_id", 7]]
  Rendered links/_link.html.erb (0.2ms)
  Rendered links/new.html.erb (2.0ms)

1 个答案:

答案 0 :(得分:0)

嗯,你需要调试它。我首先将gem pry添加到您的项目中。 然后,您应该暂时将代码更改为:

def create

  @opportunity = Opportunity.find(params[:opportunity_id])
  @link = @opportunity.links.new(link_params)
    if @link.save
      redirect_to @opportunity, notice: 'link has been added'
    else
      binding.pry
      redirect_to @opportunity, alert: 'Unable to add link'
    end
end

为了测试它,您可以照常执行添加链接操作。代码处理将在调用binding.pry的行停止。我在这里假设保存记录失败,我们输入else部分条件。

如果我假设正确,link变量将使用errors进行丰富。在binding.pry的控制台提示中,只要尝试显示它们,如果有(@link.errors

我希望有所帮助。