Rails - 表单中的条件语句识别错误的url参数

时间:2016-05-26 19:31:04

标签: ruby-on-rails if-statement request hidden-field

我在附件和用户之间存在多态关系&团队,以便用户和团队都可以上传附件。当单击“添加文件”按钮时,:team_id或:user_id作为参数传递。然后,附件#new形式中的隐藏字段告诉控制器请求是来自团队还是用户,以便将attribute_update应用于正确的模型。然而,在实践中,团队请求作为用户子动作被传递,反之亦然。关于可能出错的任何想法?

class Attachment < ActiveRecord::Base
  belongs_to :upload, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :attachments, as: :upload
end

class Team < ActiveRecord::Base
  has_many :attachments, as: :upload
end

队#节目

<%= link_to "Add Files", new_attachment_path(:team_id => @team.id), class: "btn btn-md" %>

用户#节目

<%= link_to "Add Files", new_attachment_path(:user_id => current_user), class: "btn btn-md" %>

附件#新

<% provide(:title, 'Add file') %>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@attachment) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>

      <%= f.file_field :file %>

      <% if request.path == new_attachment_path(params[:team_id]) %>
        <%= hidden_field_tag(:subaction, 'Team') %>
      <% elsif request.path == new_attachment_path(params[:user_id]) %>
        <%= hidden_field_tag(:subaction, 'User') %>
      <% end %>

      <%= f.submit "Add Files", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

附件控制器

def create
    @attachment = Attachment.create(attachment_params)
    @team = Team.find_by(params[:team_id])
    @user = User.find_by(params[:user_id])
    if @attachment.save
      if params[:subaction] == 'Team'
        @attachment.update_attribute(:upload, @team)
        flash[:success] = "Team file uploaded!"
        redirect_to @team
      elsif params[:subaction] == 'User'
        @attachment.update_attribute(:upload, @user)
        flash[:success] = "User file uploaded!"
        redirect_to current_user
      end
    else
      render 'new'
    end
end

2 个答案:

答案 0 :(得分:1)

我认为问题在于if中的attachments#new声明。 params [:team_id]和params [:user_id]都会返回一个整数,因此您的if语句无法确定请求是来自团队还是用户。建议您将params[:team_id]存储在@team_id等变量中,然后将if语句更改为以下内容:

<% unless @team_id.nil? %>
  <%= hidden_field_tag(:subaction, 'Team') %>
<% else%>
  <%= hidden_field_tag(:subaction, 'User') %>
<% end %>

但是,您可以通过在模型中使用多态关联来进一步改进这一点,如以下链接中所述:https://launchschool.com/blog/understanding-polymorphic-associations-in-rails

答案 1 :(得分:1)

更改了网址参数以传递字符串&#39;用户&#39;或者&#39;团队&#39;而不是team_id或user_id允许控制器if语句正常运行。

组#节目

if monitor == nil {
     monitor = NSEvent.addGlobalMonitorForEventsMatchingMask([.LeftMouseDownMask, .RightMouseDownMask /* and others like keyDown/Up if you want*/], handler: { (event: NSEvent) in
        NSEvent.removeMonitor(monitor!)
        monitor = nil
        popover.close()
        window = nil
    })
}

用户#节目

<%= link_to "Add Files", new_attachment_path(:upload_type => 'Team'), class: "btn btn-md" %>

附件#新

<%= link_to "Add Files", new_attachment_path(:upload_type => 'User'), class: "btn btn-md" %>