如何在accepts_nested_attributes_for中使用Carrierwave

时间:2019-06-26 06:30:00

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

我在班级消息中有这个(这是一个模型类)

  

mount_uploader的接受嵌套属性:消息图片,   PictureUploader

在message_controller类中,我有这个

def new
    @message = current_user.messages.build if logged_in?
    @message.message_pictures.build
    @reciever = User.find_by(params[:id])
  end

  def create
    @message = current_user.messages.build(message_params)

    if @message.save
      # Try saving the pictures
      flash[:success] = "Message sent"
      redirect_to messages_path
    else
      flash.now[:danger] = "Message not sent"
      render 'new'
    end
  end

和私有方法message_params(仍在message_controller中)

private
    def message_params
      params.require(:message).permit(:content, :receiver, :sender, 
        :archive, message_pictures_attributes: [:msg_img_url, :message_id])#, message_pictures_attributes:[:msg_img_url, :message_id]
    end

在消息视图中,我做到了。

<h1>Compose a new message</h1>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <%= form_for(@message, html: { multipart: true }) do |f| %>

          <%= render 'shared/error_messages', object: @message %>

          <%= f.label :content %>
          <%= f.hidden_field :receiver, value: @reciever %>
          <%= f.hidden_field :sender, value: current_user.id %>
          <%= f.text_area :content, size:"20x15" %>
          <%= f.submit "Send message", class: "btn btn-primary" %> 

          <span class="message_pictures">
            <%= f.fields_for :message_pictures do |mp| %>
              <%= mp.file_field :msg_img_url, accept: 'image/jpeg,image/gif,image/png' %>
            <% end %>   
          </span>
        <% end %>
        <%= button_to "Save message", archive_messages_path %>
        <script type="text/javascript">
            $('#message_picture').bind('change', function() {
                var size_in_megabytes = this.files[0].size/1024/1024;
                if (size_in_megabytes > 1) {
                    alert('Maximum file size is 1MB. Please choose a smaller file.');
                }
            });
        </script>

        <p>Want to go back to inbox? <%= link_to "Inbox", messages_path %></p> Or 
        <p>Want to go back to the home page? <%= link_to "Home", root_path, class: "btn btn-lg btn-primary" %></p>
    </div>
</div>

在不使用Carrierwave的情况下,它可以完美运行,这是它给的错误

  
    

MessagesController#new中的ArgumentError

         

未找到名称“ remote_message_pictures_url =”的关联。已经定义了吗?

  

指出模型类中的第5行

  
    

用于mount_uploader的accepts_nested_attributes_:消息图片,PictureUploader

  

0 个答案:

没有答案