在 html 中使用 ruby 注入时出现奇怪的语法错误

Strange syntax error when using ruby injection in html

我得到的错误是:

PagesController#main 中的语法错误

C:/Users/Sarah/RubymineProjects/MyApp/app/views/calendars/_show.html.erb:49: syntax error, unexpected ')', expecting keyword_then or ';' or '\n' ...=( if event.starts_at.monday? );@output_buffer.safe_append=' ... ^ C:/Users/Sarah/RubymineProjects/MyApp/app/views/calendars/_show.html.erb:52: syntax error, unexpected keyword_end, expecting ')' '.freeze; end ^ C:/Users/Sarah/RubymineProjects/MyApp/app/views/calendars/_show.html.erb:54: syntax error, unexpected keyword_end, expecting ')' '.freeze; end ^ C:/Users/Sarah/RubymineProjects/MyApp/app/views/calendars/_show.html.erb:364: syntax error, unexpected keyword_ensure, expecting ')' C:/Users/Sarah/RubymineProjects/MyApp/app/views/calendars/_show.html.erb:366: syntax error, unexpected keyword_end, expecting ')'

但我要编写的代码是:

<% @events.each do |event|%>
        <%= if event.starts_at.monday? %>

            <p><%= event.name %></p>
            <% end %>

        <% end %>

这真的是因为我的语法(我认为这看起来不错)还是我的代码某处有问题? 我正在 _show.html.erb(来自日历控制器)中编写此代码,这是在我的 main.html.erb(来自页面控制器)

中呈现的部分代码

这是我用来渲染部分代码的代码:

<%= render partial: '/calendars/show', locals: {} %>

这是我的控制器和模型:

class PagesController < ApplicationController

  #before_action :require_customer, only: [:main]

  def home

  end


  def main
    @events = current_customer.calendar.events
  end

end

我的日历控制器:

class CalendarsController < ApplicationController

  def new
    @calendar = Calendar.new(calendar_params)

  end

  def create
    @calendar = Calendar.new(calendar_params)
  end

private
  def calendar_params
    params.require(:customer_id)
  end


  def show
    @calendar = current_customer.calendar
    @events = @calendar.events

  end

end

我的事件控制器(仅供参考)

class EventsController < ApplicationController
  before_filter :logged_in?


  def new
    @event = Event.new
    @calendar = current_customer.calendar

  end


  def create

    @calendar = current_customer.calendar

    @event = @calendar.events.build(event_params)

    if @event.save
      redirect_to '/main' #'/main/#{@calendar.id}'
    else
      redirect_to '/compose'
      end

  end

private
  def event_params
    params.require(:event).permit(:calendar_id, :name, :starts_at, :ends_at) 
  end

还有我的日历和活动模型:

class Calendar < ActiveRecord::Base
  belongs_to :customer
  has_many :events
end


class Event < ActiveRecord::Base
  belongs_to :calendar

  end

几天来我一直被困在这个问题上,我似乎找不到解释。 谢谢!

您正在使用带有条件语句的打印标签。这一行

<%= if event.starts_at.monday? %>

应该改为

<% if event.starts_at.monday? %>

此外,您应该稍微注意正确缩进代码。

<% @events.each do |event|%>
  <% if event.starts_at.monday? %>
    <p><%= event.name %></p>
  <% end %>
<% end %>

同样适用于您的控制器。

关于 我想补充一些额外的信息。因为 Ruby 是更具表现力的语言。我想重构一下被剪掉的代码。

<% @events.each do |event|%>
    <p><%= event.name if event.starts_at.monday? %></p>
<% end %>