当我不想调用Rails helper方法时

时间:2017-03-22 16:52:20

标签: javascript ruby-on-rails ruby-on-rails-5

我正在尝试使用Ruby on Rails和JavaScript构建一个4选择的测验应用程序。 如果在问题视图中单击其中一个选择按钮,辅助方法“updateData(bool)”将更新数据库,然后您将看到没有视图转换的结果。如果您在回答后单击图表按钮,视图将转换为图表视图。

然而,辅助方法“updateData”似乎不仅被选择按钮调用,而且被图表按钮调用。它会更新数据库并根据我的期望增加问题编号。 根据console.log的输出,Chart Button不太可能调用JavaScript函数sendAnswer(ans)。

我使用Rails 5.0.1。 我很感激任何建议。谢谢!

# Return user according to remember token
def current_user
  if (user_id = session[:user_id])
    @current_user ||= User.find_by(id: user_id)
  elsif (user_id = cookies.signed[:user_id])
    user = User.find_by(id: user_id)
    if user && user.authenticated?(:remember, cookies[:remember_token])
      log_in user
      @current_user = user
    end
  end
end

# Increment the Question Number, and increment the Correct Answer Number if true
def updateData(bool)
  current_user.questionNum += 1
  current_user.correctNum += bool
  current_user.save
end

// A little helper function to map your nonstandard receive
// function into its own stream
const receivePattern = (channel, signal, selector) => 
  Observable.fromEventPattern(
    h => channel.receive(signal, h),
    h => {/*However you unsubscribe*/},
    selector
  )

export default function connectSocket(action$, store) {
  return action$.ofType(channelActions.SETUP)
    // Observable.create is usually a crutch pattern
    // Use defer or using here instead as it is more semantic and handles
    // most of the stream lifecycle for you
    .mergeMap(action => Observable.defer(() => {
        const socket = new Socket('http://localhost:4000/socket');
        const userId = store.getState().user.id;
        const channel = socket.channel(`user:${userId}`);
        const joinedChannel = channel.join();

        // Convert the ok message into a channel join
        const ok = receivePattern(joinedChannel, 'ok')
          // Just an example of doing some arbitrary mapping since you seem to be doing it 
          // in your example
          .mapTo('something')
          .map(channelActions.join);

        // Convert the error message
        const error = receivePattern(joinedChannel, 'error')
          .map(channelActions.error);

        // Since the listener methods follow a standard event emitter interface
        // You can use fromEvent to capture them
        // Rather than the more verbose fromEventPattern we used above
        const addRooms = Observable.fromEvent(channel, 'rooms:add')
          .map(channelActions.add);

        const somethingElse = Observable.fromEvent(channel, 'something:else')
          .map(channelActions.somethingElse);

        // Merge the resulting stream into one
        return Observable.merge(ok, error, addRooms, somethingElse);
      });
  );
};

1 个答案:

答案 0 :(得分:0)

在上面的html代码中,嵌入式Ruby<%updateData%>在生成HTML时执行。

我应该通过Button Click Event调用Controller Action,然后通过Action调用helper方法。