在我看来,用户需要使用 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:照片
- 编号
- photo_type_id(引用
photo_types
表中的id
)
表 2:photo_types
- 编号
- 照片类型
用户可以从下拉菜单中选择照片类型,我想通过用户输入在 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/