ruby-on-rails - 在 Rails View 中将变量分配给用户输入

标签 ruby-on-rails ruby

在我看来,用户需要使用 collection_select 输入一些数据。

我知道可以在 Controller 中使用 params[] 访问数据。

但是我如何在用户选择一个值后立即访问该值?

这就是我正在尝试做的(不起作用):

<%= f.collection_select :photo_type, Upload::PHOTOTYPE, :to_s, :to_s, :include_blank => false, :id => "phototype"%>
<%= f.hidden_field :photo_id, :value => Photo.find_by_type(params[:photo_type]).id %>

我的问题是如何访问 collection_select 中的 :photo_type

编辑

我尝试过使用 jQuery,但我不知道如何将 js 变量导出到 View :

<script type="text/javascript">
    $("#phototype").change(function() {
        var phototype = $('#phototype').val()
    });
 </script>

更新

我的数据库中有两个表:

表 1:照片

  1. 编号
  2. photo_type_id(引用photo_types表中的id)

表 2:photo_types

  1. 编号
  2. 照片类型

用户可以从下拉菜单中选择照片类型,我想通过用户输入在 photo_types 表中找到 photo_type_id 然后插入 photo_type_id 放入 photos

根据 codeit,我改变了我的 Controller :

def create
    @photo = photo.new(params[:photo])
    photo_type_id = PhotoType.find_by_type(params[:photo_type]).id
    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'photo was successfully created.' }
        format.json { render json: @photo, status: :created, location: @photo }
      else
        format.html { render action: "new" }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
end

最佳答案

我认为您正在使用 hidden_​​field 将值发送到下一个操作。你为什么不在 Controller 操作中做同样的事情:

  def create
    @photo = Photo.new(params[:photo])
    @photo.photo_type_id = PhotoType.find_by_type(params[:photo][:photo_type]).id
    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'photo was successfully created.' }
        format.json { render json: @photo, status: :created, location: @photo }
      else
        format.html { render action: "new" }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

查看:

  <%= f.collection_select :photo_type, Upload::PHOTOTYPE, :to_s, :to_s, :include_blank => false, :id => "phototype"%>

建议:标准做法是避免在 View 中查询。

关于ruby-on-rails - 在 Rails View 中将变量分配给用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987244/

相关文章:

ruby-on-rails - 铁路时间 :Minutes Dropdowns

ruby-on-rails - 我应该将 @notifications 放入哪个 Controller ?

ruby-on-rails - Rails3 管理界面框架

ruby - 使用 Ruby 解析 XML

ruby-on-rails - ROR 应用程序中未定义的局部变量或方法

ruby - CI 与 Hudson 和 Cucumber

ruby - 可以分配给变量的最低内存占用对象是多少?

ruby-on-rails - 将应用程序部署到两个不同的服务器,具有不同的 production.rb 内容

ruby-on-rails - 如何在 Rails 中动态调用或调用类?

ruby - 检测哈希中是否存在键值对