小编use*_*683的帖子

Rails 4:collection_select没有插入'class'属性?

我在这里错过了什么?我正在使用Rails 4.0.0并尝试新的Bootstrap 3.0.0rc1.我有一个简单的"食谱盒"应用程序,它有一个食谱模型和一个分类模型,可以在食谱上提供"类别"字段.在食谱#new视图中,我定义了以下字段:

<h1>Create New Recipe</h1>
<%= form_for @recipe, html: { class: 'form-horizontal' } do |f| %>
<fieldset>
  <legend>Main Information</legend>
  <div class="form-group">
    <%= f.label :name, "Recipe name", class: "col-lg-2 control-label" %>
    <div class="col-lg-6">
      <%= f.text_field :name, class: "form-control" %>
    </div>
  </div>
<div class="form-group">
  <%= f.label :category_id, class: "col-lg-2 control-label" %>
  <div class="col-lg-6">
    <%= f.collection_select :category, Category.all, :id, :name, class: "form-control", prompt: "Select a category" %>
  </div>
</div>
...
Run Code Online (Sandbox Code Playgroud)

text_field帮助器呈现格式正确的标记,并带有class属性.但是,无论我如何构造select或collection_select助手,我似乎无法让Rails给我一个包含class属性的东西.上面的代码给了我这个:

<select id="recipe_category" name="recipe[category]"><option value="">Select a category</option>

...
Run Code Online (Sandbox Code Playgroud)

所以提示通过,但类attrib没有,所以它看起来像html_options哈希的一部分被识别.但是没有应用Bootstrap样式.如果我在类中使用大括号{}无关紧要:"form-control"与否.如果我在collection_select params周围使用parens,无关紧要.也可以选择帮助器.

任何人都可以建议吗?你也看到了这个吗?

forms actionviewhelper ruby-on-rails-4

15
推荐指数
2
解决办法
2万
查看次数

Rails 4.0和Cocoon:fields_for下的嵌套字段不会出现在Edit中

希望有人可以在这里建议修复.我对Rails相当新,并探索Rails 4.0中的变化.我在Rails 4.0中构建了这个简单的食谱书应用程序.我有食谱的主要模型(名称,cook_time,oven_temp,说明等).因为一些食谱可能有5种成分而其他食谱可能有20种,我想在一个带有has_many关联的单独模型中打破成分.所以食谱has_many成分和accepts_nested_attributes_for:成分.以下是模型:

recipe.rb

class Recipe < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
  has_many :ingredients, :dependent => :destroy

  validates :name, presence: true, length: { maximum: 50 }

  accepts_nested_attributes_for :ingredients, 
                :reject_if => lambda { |a| a[:name].blank? },
                            :allow_destroy => true
end
Run Code Online (Sandbox Code Playgroud)

ingredient.rb

class Ingredient < ActiveRecord::Base
  belongs_to :recipe
end
Run Code Online (Sandbox Code Playgroud)

提醒:Rails 4.0不再使用attr_accessible,而是使用强params将赋值移动到控制器中.

recipes_controller.rb

class RecipesController < ApplicationController
  before_action :find_recipe, only: [:show, :edit, :update, :destroy]
  before_action :set_current_user, except: [:index, :show]
  respond_to :html, :js

  ...

  def edit
  end

  def update
    if @recipe.update_attributes(recipe_params)
      redirect_to @recipe
    else …
Run Code Online (Sandbox Code Playgroud)

gem nested-attributes fields-for ruby-on-rails-4 cocoon-gem

3
推荐指数
1
解决办法
3375
查看次数