【问题标题】:Ruby on Rails, pass Image from one object to another or from NEW to CREATERuby on Rails,将图像从一个对象传递到另一个对象或从 NEW 传递到 CREATE
【发布时间】:2012-04-07 15:05:55
【问题描述】:

我对 Ruby on Rails 还是很陌生。

我更改了这个帖子,因为我意识到我在错误的一端寻找我的问题的解决方案。

这是我的问题:

我有一个类 ProfileProposal,我用它上传了一张图片(使用 CarrierWave)。 现在我想将 ProfileProposal 转换为另一个名为 Profile 的类。 所以我将所有信息传递给 Profile 的 NEW-Form。

适用于字符串,但不适用于图像。

我已经尝试过/做过的事情:

将图像作为 GET 参数传递给 Create 方法:

<%= form_for @profile, :url => { :action => "create", :controller => "profiles", :image => @profile_proposal.image } do |f| %>

#

现在可以使用,所以我确实有图片网址。

以下是无效的:

@profile = Profile.new(params[:profile], :image => new_image_url)
# OR
@profile.image = new_image_url

@profile.image 仍然具有 Carrierwave 给出的默认值。

提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 carrierwave


    【解决方案1】:

    我来自使用回形针,而不是载波,所以我会尽量保持这个高水平。但我有一个想法给你。也许您可以在新附件存在之前设置它的文件名,然后将图像移动到该路径。使用回形针,效果如下:

    @profile.image_file_name = "profile.jpg"
    # creates the directory of the new path.  There's probably a better way to do this:
    FileUtils.mkdir_p @profile.image_file_path.gsub(/[^\/]*$/,'')
    FileUtils.mv @profile_proposal.image_path @profile.image_path
    

    【讨论】:

    • 嘿,移动文件可以正常工作,创建目录也可以。不工作的是更改文件名:(
    • 嘿,我改变了我的问题,希望你们能帮助我
    【解决方案2】:

    您应该在 Profile 表单中嵌入一个隐藏字段,通过某个 ID 引用 ProfileProposal。然后在处理表单服务器端时,在所有内容都经过验证并准备好保存后,您应该使用一些读/写方法将图像从ProfileProposal 实例复制到Profile 实例。我不确定 CarrierWave 希望您如何做到这一点。

    【讨论】:

    • 一个配置文件可能有多个提案,因此:profile has_many profile_proposals。我可以在配置文件表单中传递参数,我仍然知道图像。但是在创建中我无法设置图像:-/
    【解决方案3】:

    我终于解决了这个问题,通过使用回形针并创建一个新实例

    Profile.create(:name => @profile_proposal.name, :image => @profile_proposal.image)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      • 2016-09-06
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      相关资源
      最近更新 更多