繁体   English   中英

如何在索引视图中显示Date :: DAYNAMES?

[英]How to Display Date::DAYNAMES In Index View?

当用户在_form中选中他“致力于”的:days ,我希望他的日子显示在索引中 ,但是当前当用户加载索引页面时<%= habit.days %>空白,我看到当用户单击提交时,复选标记消失了。

_形成

  <%= f.label "Committed to:" %> <% Date::DAYNAMES.each do |day| %> <%= f.check_box :days, {}, day %> <%= day %> <% end %> 

指数

 <% @habits.each do |habit| %> <td><%= habit.days %></td> <% end %> 

我是否需要向控制器模型添加代码?

调节器

 class HabitsController < ApplicationController before_action :set_habit, only: [:show, :edit, :update, :destroy] before_action :correct_user, only: [:edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] def index @habits = Habit.all end def show end def new @habit = current_user.habits.build end def edit end def create @habit = current_user.habits.build(habit_params) if @habit.save redirect_to @habit, notice: 'Habit was successfully created.' else render action: 'new' end end def update if @habit.update(habit_params) redirect_to @habit, notice: 'Habit was successfully updated.' else render action: 'edit' end end def destroy @habit.destroy redirect_to habits_url end private def set_habit @habit = Habit.find(params[:id]) end def correct_user @habit = current_user.habits.find_by(id: params[:id]) redirect_to habits_path, notice: "Not authorized to edit this habit" if @habit.nil? end def habit_params params.require(:habit).permit(:missed, :left, :level, :days, :date_started, :trigger, :action, :target, :positive, :negative) end end 

模型

 class Habit < ActiveRecord::Base belongs_to :user validates :action, presence: true end 

D b

 class CreateHabits < ActiveRecord::Migration def change create_table :habits do |t| t.string :missed t.datetime :left t.string :level t.datetime :days t.datetime :date_started t.string :trigger t.string :action t.string :target t.string :positive t.string :negative t.boolean :mastered t.timestamps null: false end end end 

UPDATE

现在,索引视图通过以下答案将其引出:

[“周一,周二,周三,周四”, ””]

我们怎样才能使它看起来像这样?

周一,周二,周三,周四

您没有正确使用f.check_box ,该帮助程序设计为只能在单个属性上使用,而不能在迭代器中使用。

您可能想要类似的东西:

<%= f.collection_check_boxes :days, Date::DAYNAMES, :downcase, :to_s %>

更新

在对问题进行一些评论和更新之后,我添加了以下评论,我将其放在此处,以便答案与问题匹配:

您的迁移表明, daysdatetime字段,因此无法使用字符串数组。 为了使这项工作(尽管这可能不是您想要的,会破坏其他东西吗?),您需要将该字段转换为text类型,即。 在迁移中使用t.text :days ,然后在模型中使用serialize :days, Array创建一个序列化字段。

另一个更新

如果您检查日志,则会看到类似"Unpermitted parameter: days" -这是因为您需要指定包含子结构(如数组或哈希)的任何内容,因此在habit_params而不是:days需要有:days => []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM