为多态关联提交表单和创建操作

时间:2012-01-20 01:17:56

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 polymorphic-associations

我收到了帮助Setting up a polymorphic association

我现在无法实施提交表单并创建操作。用户只需要关注和取消关注每个模型。

在我的关注控制器中

 class FollowsController < ApplicationController
       before_filter :find_supports

  def create
    @relation = find_supports
    @follow = @relation.find(params[:follow])
    current_user.follows.follow!(@follow)
      respond_to do |format|
      format.html { redirect_to :back }
      format.js
    end
  end

 def destroy
   @follows = Follow.find(params[:id]).followable
    current_user.unfollow!(@follows)
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    end
 end

  private
  def find_supports
    params.each do |name, value|
      if name =~ /(.+)_id$/
         return $1.classify.constantize.find(value)
     else
       nil
     end
    end
  end
end 

在我的Follow Form中,在我的多态模型上呈现

修改

 <%= form_for @cause.follows.build(params[:follow]) do |f| %>
  <div><%= f.hidden_field :followable_id %></div>
  <div><%= f.hidden_field :followable_type %></div>
  <div><%= f.hidden_field :follower_id %></div>

 <div class="create-button"><%= f.submit "Follow" %></div>
    <% end %>  <!-- I now get the values for followable_id and followable_type, but it         
               wont get grab the follower_id and I get an error in the create action -->

在我的用户模型中,我有这三种方法

   def following?(follow)
       follows.find_by_followable_id(follow)
   end
   def follow!(followable)
       follows.create![]    ##I have tried many different params here
   end
   def unfollow!(followable)
       follows.destroy(params[:followable_id]).destroy
   end

我无法正确保存follower_id,followable_id和followable_type。有什么建议? 在此先感谢,我花了很多时间。

1 个答案:

答案 0 :(得分:1)

以下是我解决问题的方法。答案是使用AJAX和Devise辅助方法current_user

表格部分

  <%= form_for @relation.supports.build(params[:support]), :remote => true do |f| %>
   <div><%= f.hidden_field :supporter_id, :value => current_user.id %></div>
    <div><%= f.hidden_field :supportable_id %></div>
   <div><%= f.hidden_field :supportable_type %></div>
   <%= f.submit "Support", :class => "support-button" %>
   <% end %>

我的控制器

class SupportsController < ApplicationController
before_filter :find_relation

def create
  @relation.supports.create!(params[:support])
respond_to do |format|
  format.html { redirect_to :back }
  format.js
 end
end

def destroy
 @relation.supports.find(params[:id]).destroy
 respond_to do |format|
   format.html { redirect_to :back }
   format.js
 end
end

private
 def find_supports(instance_params)
   class_name = instance_params["supportable_type"].classify.constantize
   class_name.find(instance_params["supportable_id"])
 end 

def find_relation
  @relation = find_supports(params[:support])
end
end

此外,在呈现表单的所有控制器中添加before_filter以查找正确的对象。这将允许您对所有多态类使用相同的表单部分。

    def find_supports
       @relation = YourClass.find(params[:id])
    end