是否可以仅将rails表单元素部分放置? [英] Is it possible to put just a rails form element in a partial?

查看:75
本文介绍了是否可以仅将rails表单元素部分放置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有一个选择框,供用户选择场地".如您所料,此选择框为表格形式.我在页面的某处还有一个通过AJAX创建新场所的动作.创建新场所后,我想更新场所选择框以反映这一点.

My app has a select box for users to choose a "venue". This select box is, as you would expect, in a form. I also have an action somewhere on the page that creates a new venue via AJAX. After the new venue is created, I would like to updated the venue select box to reflect this.

我的解决方案是将选择框放在局部中,并通过控制器中的create动作渲染局部.

My solution was to put the select box in a partial and render the partial from the create action in the controller.

 <div id="venue_select" style="clear: both;">
    <%= render :partial => 'venue/venue_select_box' %>
 </div>

部分看起来像这样:

<%= f.collection_select :venue_id, @user_venues, :id, :name, :prompt => 'Select a venue' %>

其中f是表单引用:

<% form_for :shows do |f| %>

问题是f在局部变量中未定义,因此出现错误.一种解决方案是包括整个表格,但是我觉得那不是必须的,因为我没有更新整个表格.关于如何解决这个问题有什么想法吗?

The problem is that f is undefined in the partial, so I get an error. One solution would be to include the entire form, but I feel like that should not be necessary because I am not updating the entire form. Any ideas on how to go about this?

推荐答案

这些都是不错的选择,但我认为我觉得最简单.基本上,我只是将名称硬编码在collection_select中,所以我不需要"f"变量:

These are all great options but I think I found the easiest. Basically, I just hard coded the name in the collection_select so I would not need the "f" variable:

<%= collection_select 'shows[venue_id]', :venue_id, @user_venues, :id, :name, { :prompt => 'Select one of your previous venues' } %>

然后我的VenueController如下:

Then my VenueController is as follows:

class VenueController < ApplicationController
  layout 'main'
  before_filter :login_required, :get_user

  def create
    begin
      venue = @user.venues.create(params[:venue])
      @user_venues = @user.venues
      render :partial => 'venue_select_box', :success => true, :status => :ok
    rescue ActiveRecord::RecordInvalid => invalid
      flash[:errors] = invalid.record.errors
      render :text => '', :success => false, :status => :unprocessable_entity
    end
  end

end

如果此方法由于任何原因是不好的做法,请告诉我,我们将很乐意为您提供答案.

If this method is bad practice for any reason, please let me know and I will happily credit you for the answer.

这篇关于是否可以仅将rails表单元素部分放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆