Rails 4:在字符串中嵌入链接

时间:2017-02-11 11:36:02

标签: ruby-on-rails string ruby-on-rails-4 hyperlink link-to

我的一个控制器中有一个字符串字段,这是一条消息。我想在其中嵌入一个可点击的链接。

这样的东西在视图中起作用:

public class BaseActivity extends Activity {
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();
        int contentViewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();

        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(BaseActivity.this);

        if(heightDiff <= contentViewTop){
            onHideKeyboard();

            Intent intent = new Intent("KeyboardWillHide");
            broadcastManager.sendBroadcast(intent);
        } else {
            int keyboardHeight = heightDiff - contentViewTop;
            onShowKeyboard(keyboardHeight);

            Intent intent = new Intent("KeyboardWillShow");
            intent.putExtra("KeyboardHeight", keyboardHeight);
            broadcastManager.sendBroadcast(intent);
        }
    }
};

private boolean keyboardListenersAttached = false;
private ViewGroup rootLayout;

protected void onShowKeyboard(int keyboardHeight) {}
protected void onHideKeyboard() {}

protected void attachKeyboardListeners() {
    if (keyboardListenersAttached) {
        return;
    }

    rootLayout = (ViewGroup) findViewById(R.id.rootLayout);
    rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

    keyboardListenersAttached = true;
}

@Override
protected void onDestroy() {
    super.onDestroy();

    if (keyboardListenersAttached) {
        rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);
    }
}
}

但在控制器中无法存储<% dd = "Click on link to #{link_to 'View ', "www.google.com"} asdad" %> <%= dd.html_safe %> ,我收到此错误:

dd

我也尝试了NoMethodError (undefined method `link_to' for ...

to_s

但仍然是同样的错误。请帮助我知道如何在rails 4中将链接嵌入到字符串中。

1 个答案:

答案 0 :(得分:1)

尝试

控制器代码中的

view_context.link_to '...', '...'