私は、添付ファイルとユーザの間の多様な関係を持っています。&チームは、ユーザとチームの両方が添付ファイルをアップロードできるようにします。 : "ファイルの追加"ボタンをクリックすると:team_idまたは:user_idがパラメータとして渡されます。次に、attachments#newフォームの隠しフィールドは、attribute_updateを適切なモデルに適用できるように、要求がチームまたはユーザーから来ているかどうかをコントローラに通知します。しかし実際には、チームの要求はユーザーのサブアクションとして配信され、その逆もあります。何が間違っている可能性がありますかに関する任意のアイデア?Rails - 間違ったURLパラメータを認識するフォームの条件文
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" %>
添付ファイルを表示するには、show
<% 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
私は '多型' と '多項式' の関係を置き換えます。あなたのパラメータは、Railsの意味で多態的な関係を定義したようには見えません。しかし、私はなぜ「逆の」行動が現れるのか分かりません。この行動をどうやって分析しましたか? – Raffael
ありがとうございます。チームページから添付ファイルを追加すると、サブアクションは「ユーザー」として登録されます。ユーザーページから添付ファイルを追加すると、サブアクションは「チーム」として登録されます – ncarroll
定義:「 – Raffael