【问题标题】:Rails: duplicating information into another model if conditions metRails:如果条件满足,将信息复制到另一个模型中
【发布时间】:2013-05-22 04:37:07
【问题描述】:

我在表单上有一个带有复选框的文章列表。选中某个框时,所选文章的正文将复制到 x 文本区域之一。

如果用户想要更改文本区域中的文章正文,我需要通过我的控制器将该更改发送到新的 Rails 模型(称为Edit)。

我已经创建了记录,我只需要应用程序将更改记录到新的Edit 记录中。这是我的相关控制器代码:

def new
  @template = Template.find(params[:template])
  @article_count = @template.pages-1
  @doc = Doc.new
  @doc.template_id = @template.id
  @doc.user_id = current_user.id
  @articles = current_user.brand.articles
  respond_to do |format|
    format.html
    format.json { render json: @doc }
  end
end

创建

def create
  @doc = Doc.new(params[:doc])
  respond_to do |format|
    if @doc.save
      #make editable version
      if current_user.brand.try(:editable?)
        @doc.articles.each do |article|
          @edit = Edit.new
          @edit.name = article.name
          @edit.video = article.video
          #something here to get the bodies of the text areas
          @edit.article_id = article.id
          @edit.doc_id = @doc.id
          @edit.user_id = current_user.id
          @edit.save
        end
      end
      @doc.create_activity :create, owner: current_user
      format.html { redirect_to share_url(@doc.user.ftp, @doc) }
      format.json { render json: @doc, status: :created, location: @doc }
    else
      format.html { render action: "new" }
      format.json { render json: @doc.errors, status: :unprocessable_entity }
    end
  end
end

这是在视图中制作文本区域的代码。

<% @article_count.times do |article| %>
  <div id="edit<%= article %>" class="tab-pane <%= "active" if article == 0 %>">
    <%= text_area_tag("edit[#{article}][body]") %>
  </div>
<% end %>

为每篇文章创建记录,但我似乎无法保存文本区域中的编辑。这是一种嵌套形式的排列。任何帮助都将不胜感激。干杯!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 model-view-controller nested-forms


    【解决方案1】:

    我通过将表单分成两页解决了这个问题:一个处理选择,第二个处理编辑。鉴于Doc 有很多edits,这是我为表单的第二部分制作的方法:

    def edit_content
      @doc = Doc.find(params[:id])
      if !@doc.edits.exists?
        @doc.articles.reverse.each do |article|
          @doc.edits.build(:body => article.body)
        end
      end
    end
    

    希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 2021-04-10
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多