0

我在下面有一组通过表单提交的参数

Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyMkh1eJ7WxYC978XKjdsyGOeGDvi6RTIOSGb9KMqkc=", "link"=>{"category_id"=>"1", "comment"=>"", "url"=>"yahoo.com "}, "type"=>"html", "original_url"=>"http://yahoo.com", "url"=>"http://www.yahoo.com/", "title"=>"Yahoo!", "description"=>"Welcome to Yahoo!, the world's most visited home page. Quickly find what you're searching for, get in touch with friends and stay in-the-know with the latest news and information.", "favicon_url"=>"http://www.yahoo.com/favicon.ico", "provider_url"=>"http://www.yahoo.com", "provider_display"=>"www.yahoo.com", "provider_name"=>"Yahoo", "safe"=>"true", "html"=>"", "thumbnail_url"=>"", "object_type"=>"link", "image_url"=>"", "category_id"=>"1"}

我想在属于类别模型的链接模型中创建一个新的“链接”记录。我在链接控制器中的“创建”操作如下所示

  def create
    @category = Category.find_by_id(params[:category_id])
    @link = @category.links.build(params[:link])
    @link.user_id = current_user.id
    respond_to do |format|
        if @link.save
            links_attributes = params.slice(:original_url, :title, :description, :favicon_url, :provider_url, :provider_display, :thumbnail_url, :object_type)
            @link.update_attributes(links_attributes)
        else 

        end
    end     
  end

如果我只是在没有更新属性的情况下执行@link.save,它只会保存评论、url 和类别 ID。但是,上面创建了 2 条记录,一条评论、url 和 category_id,另一条包含所有数据。

我怎样才能确保这只会创建一个包含所有信息的记录?

更新 如果我可以用 3 个参数创建记录,然后用剩余的参数(links_attributes)更新它,我会很好......只是不知道该怎么做。

这是我提交时得到的输出:

Started POST "/categories/1/links" for 127.0.0.1 at 2013-01-11 12:43:44 -0500
Processing by LinksController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyMkh1eJ7WxYC978XKjdsyGOeGDvi6RTIOSGb9KMqkc=", "link"=>{"category_id"=>"1", "comment"=>"", "url"=>"bloomberg.com "}, "type"=>"html", "original_url"=>"http://bloomberg.com", "url"=>"http://www.bloomberg.com/", "title"=>"Business, Financial & Economic News, Stock Quotes", "description"=>"Bloomberg is a premier site for business and financial market news. It delivers world economic news, stock futures, stock quotes, & personal finance advice.", "favicon_url"=>"http://www.bloomberg.com/favicon.ico", "provider_url"=>"http://www.bloomberg.com", "provider_display"=>"www.bloomberg.com", "provider_name"=>"Bloomberg", "safe"=>"true", "html"=>"", "thumbnail_url"=>"http://www.bloomberg.com/image/is2KySnyVWmA.jpg", "object_type"=>"link", "image_url"=>"", "category_id"=>"1"}
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "links" ("category_id", "comment", "created_at", "description", "favicon_url", "object_type", "original_url", "points", "profile_link", "provider_display", "provider_url", "thumbnail", "thumbnail_url", "title", "updated_at", "url", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["category_id", "1"], ["comment", ""], ["created_at", Fri, 11 Jan 2013 17:43:

Started POST "/categories/1/links" for 127.0.0.1 at 2013-01-11 12:43:44 -0500
Processing by LinksController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyMkh1eJ7WxYC978XKjdsyGOeGDvi6RTIOSGb9KMqkc=", "link"=>{"category_id"=>"1", "comment"=>"", "url"=>""}, "commit"=>"Post", "category_id"=>"1"}
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSE44 UTC +00:00], ["description", "Bloomberg is a premier site for business and financial market news. It delivers world economic news, stock futures, stock quotes, & personal finance advice."], ["favicon_url", "http://www.bloomberg.com/favicon.ico"], ["object_type", "link"], ["original_url", "http://bloomberg.com"], ["points", nil], ["profile_link", nil], ["provider_display", "www.bloomberg.com"], ["provider_url", "http://www.bloomberg.com"], ["thumbnail", nil], ["thumbnail_url", "http://www.bloomberg.com/imRT INTO "links" ("category_id", "comment", "created_at", "description", "favicon_url", "object_type", "original_url", "points", "profile_link", "provider_display", "provider_url", "thumbnail", "thumbnail_url", "title", "updated_at", "url", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["category_id", "1"], ["comment", ""], ["created_at", Fri, 11 Jan 2013 17:43:44 UTC +00:00], ["description", nil], ["favicon_url", nil], ["object_type", nil], ["original_url", nil], ["points", nil], ["profile_link", nil], ["provider_display", nil], ["provider_url", nil], ["thumbnail", nil], ["thumbnail_url", nil], ["title", nil], ["updated_at", Fri, 11 Jan 2013 17:43:44 UTC +00:00], ["url", ""], ["user_id", 1]]
   (1.1ms)  commit transaction
  Rendered links/create.js.erb (0.0ms)
Completed 200 OK in 8ms (Views: 3.9ms | ActiveRecord: 1.6ms)
age/is2KySnyVWmA.jpg"], ["title", "Business, Financial & Economic News, Stock Quotes"], ["updated_at", Fri, 11 Jan 2013 17:43:44 UTC +00:00], ["url", "bloomberg.com "], ["user_id", 1]]
   (2.5ms)  commit transaction
  Rendered links/create.js.erb (0.0ms)

这是我的表格:

<%= form_for([@category, @category.links.build], :remote => true, :class => "form-horizontal") do |f| %>
    <%= f.hidden_field :category_id, :value => params[:id] %>
    Comment: <%= f.text_field :comment %><BR>
    Link: <%= f.text_field :url %>
    <%= f.submit "Post", :class => "btn", :disable_with => '...', :id => "new_link_button" %>
<% end %>

<div class="selector" style="width:350px;margin:-30px 0px 0px 0px;"></div>
<!-- Placeholder that tells Preview where to put the loading icon-->
<div class="loading">
    <img src='http://embedly.github.com/jquery-preview/images/loading-rectangle.gif'>
</div>


<script>


$('#link_url').preview({ key:'60f1dcdf3258476794784148a6eb65e7', // Sign up for a key: http://embed.ly/pricing

      selector : {type:'rich'},
      preview : {
        submit : function(e, data){
          $.ajax({
            dataType: 'script',
            url: this.form.attr('action'),
            type: 'POST',
            data: data
          });
        },
      },
      autoplay : 0,
      maxwidth : 350,
      display : {display : 'rich'}
});

$('#new_link_button').click(function(e) {
    e.preventdevault();
    $('.new_link').submit();
    return false;
});

</script>

这是我的路线:

  resources :categories, :only => [:new, :show, :create, :edit, :update] do
    resources :links, :only => [:new, :show, :create, :edit, :update]
    resources :industries, :only => [:new, :show, :create, :edit, :update]
    resources :territories, :only => [:new, :show, :create, :edit, :update]
  end
4

3 回答 3

0

在保存之前尝试设置它们。

def create
  @link = Link.new(params[:link])
  @link.category_id = params[:category_id]
  @link.original_url = params[:original_url]
  @link.title = params[:title]
  @link.description = params[:description]
  @link.user_id = current_user.id
  # etc...
  respond_to do |format|
    if @link.save
      # do things...
    else 
      # do other things...
    end
  end
end
于 2013-01-11T16:48:29.547 回答
0

首先,您不需要调用@link.savethen @link.update_attributes,因为如果它不存在,@link.update_attributes它将保存在您的数据库中。@link

从您发布的日志中,您的控制器似乎收到了两个发布请求,这就是它创建两个对象的原因,我认为原因是发生了两次提交:一个是提交的表单,另一个是内部的 ajax 请求你的$('#link_url').preview(...代码。

于 2013-01-11T18:00:56.150 回答
0

我认为您的表单的构建方式存在问题。正如您在发布的参数中看到的那样,params[:link]仅包含您尝试保存在链接上的数据的子集:

"link"=>{"category_id"=>"1", "comment"=>"", "url"=>"yahoo.com "}

其余的都在 params 数组的顶层:

Parameters: {... "original_url"=>"http://yahoo.com", "url"=>"http://www.yahoo.com/", "title"=>"Yahoo!", "description"=>"Welcome to Yahoo!..." ...}

你应该看看你是如何使用 form_for 来构造你的表单的,并确保它被正确地用于附加参数。

编辑:

如果您无法编辑表单,则可以在控制器中执行此操作:

@link.user_id = current_user.id
links_attributes = params.slice(:original_url, :title, :description, :favicon_url, :provider_url, :provider_display, :thumbnail_url, :object_type)
@link.attributes = links_attributes
respond_to do |format| 
   if @link.save
      ...
于 2013-01-11T16:36:51.760 回答