在同一视图中显示的多态关联的表单?

时间:2012-11-18 00:59:27

标签: ruby-on-rails

我有三个模型:Post, ReplyVoteVotePostReply的多态关联:

routes.rb中:

   resources :posts do
    resources :votes
    resources :replies do
      resources :votes
    end
  end
  resources :votes,         only: [:create, :destroy]

votes_controller.rb:

  def create
    @votable = find_votable
    @vote = @votable.votes.create(params[:vote])
    if @votable.save
     # vote saved
    else
      render :action => 'new'
    end
  end

  private

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

posts_controller.rb:

def show
    @post = Post.find(params[:id])
    @replies = @post.replies.paginate(page: params[:page])
    @reply = @post.replies.build
    @votable = ? # not sure what to add here
    @vote = Vote.new
 end

帖/ show.erb:

  <%= form_for ([@votable, @vote]) do |f| %>
    <p>
      <%= f.label :polarity %><br />
      <%= f.text_field :polarity %>
      <%= f.label :user_id %><br />
      <%= f.text_field :user_id %>
    </p>
    <p><%= f.submit "Submit" %></p>
  <% end %>

  <%= render 'replies/form' %>

回复/ form.rb:

  <%= form_for ([@votable, @vote]) do |f| %>
    <p>
      <%= f.label :polarity %><br />
      <%= f.text_field :polarity %>
      <%= f.label :user_id %><br />
      <%= f.text_field :user_id %>
    </p>
    <p><%= f.submit "Submit" %></p>
  <% end %>

我不确定如何在帖子控制器中定义@votable,因此它对帖子的投票表单Post.find(params[:id])和投票表格的Reply.find(params[:id])。这很难,因为postsreplies都在同一个展示视图中。

有没有解决方法? (或者有更好的方法吗?就像在投票控制器中制作@votable变量一样,在后置控制器中可用吗?)

1 个答案:

答案 0 :(得分:0)

您尝试的是嵌套表单。多态的关系不应该影响如何实现它。试着看看轨道广播

http://railscasts.com/episodes/196-nested-model-form-part-1

并检查此宝石

https://github.com/ryanb/nested_form

它的旧版本可能有更新的宝石和方法。