在Rails视图中显示Active Record默认值

时间:2015-10-06 11:25:50

标签: ruby-on-rails ruby activerecord erb

如何获取要在我的视图中呈现的活动记录列的默认值?

我在content:string表格中为first_lists列创建了默认值:

create_table "first_items", force: :cascade do |t|
t.string     "content",    default: "Add a task"
t.integer  "list_id"
t.datetime "created_at",                        null: false
t.datetime "updated_at",                        null: false
end

然后在first_items_controller.rb中:

class FirstItemsController < ApplicationController

def update
  @item = FirstItem.find(params[:id])
  if @item.update(item_params)
    render    
  else
    @list = @item.list
    render 'list/show'
  end
end

private
  def item_params
    params.require(:first_item).permit(:content)
  end
end

然后我尝试将视图渲染为列表/显示页面中的部分视图:

<section class="todoapp">
  <header class="header">
    <h1 id="list-h1"><%= @list.title %></h1>
    <!-- <h1 id="list-h1"><%#= @list.name %></h1> -->
  </header>
  <section class="main">
    <ul class="todo-list">
      <%= render @list.first_items %>
      <%= render @list.second_items %>
      <%= render @list.third_items %>
      <%= render @list.fourth_items %>
    </ul>
    <button type="submit" class="btn btn-warning btn-lg" id="save-button">Save</button>
  </section>
</section>

_first_items.html.erb

<li class="item" data-id-first="<%= first_item.id %>">
    <div class="panel panel-danger box-shadow--8dp">
      <div class="panel-heading">
        <h5 class="panel-header-title">Mission Critical Task One</h5>
      </div>
      <div class="panel-body">
        <%= form_for(first_item, :remote => true) do |f| %>
            <%= f.text_field :content, :class => "edit form-control", :id => "first-form" %>
          <% end %>
      </div>
      <div class="panel-footer"><input class="toggle panel-title" id="form-input" type="checkbox" unchecked=""> Complete</div>
    </div>
</li>

当我去`lists /:id&#39;页面上没有呈现任何内容。我希望我的默认值会填写在表单中。

使用此设置,如果我进入控制台并手动创建:content,我可以获得所需的输出。有没有办法用默认列字符串实例化这些部分?

EDIT 这是lists_controller.rb

class ListsController < ApplicationController

  def index
    @lists = List.all
    @list = List.new
  end

  def create
    @list = List.new(list_params)
      if @list.save
        if request.xhr?
          render :layout => false
        else
          redirect_to root_path
      end
    else
      @lists = List.all
      render :index
    end
  end

  def show
    @list = List.find(params[:id])
  end

  private
    def list_params
      params.require(:list).permit(:name)
    end

end

2 个答案:

答案 0 :(得分:0)

您只想在text_field对象上使用value这样的参数:

<%= f.text_field :content, :class => "edit form-control", :id => "first-form", value: first_item.content %>

答案 1 :(得分:0)

我只想回答你问题的第一行。

MyKlass.columns_hash["column_name"].default

或者,在您的示例中,

FirstList.columns_hash["content"].default