jeudi 26 mai 2016

Rails - Conditional statement in form recognizing wrong url paramater

I have a polynomial relationship between Attachments and Users & Teams so that both users and teams can upload attachments. The :team_id or :user_id is passed along as a param when the "Add file" button is clicked. Then, a hidden field in the attachments#new form tells the controller if the request is coming from a Team or User so that attribute_update can be applied to the proper model. In practice, however, the team request is being delivered as user subaction and vice versa. Any ideas as to what may be going wrong?

team#show

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

user#show

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

attachments#new

<% 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>

attachment controller

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

Aucun commentaire:

Enregistrer un commentaire