我有两个模型,歌曲和投票,歌曲有很多票.我想选择所有歌曲并计算每张歌曲的票数.
使用mix gen任务生成的SongController中的索引操作已修改为:
def index(conn, _params) do
query = from s in Song, select: %{id: s.id, name: s.name, artist: s.artist}
songs = Repo.all(query)
render(conn, "index.html", songs: songs)
end
Run Code Online (Sandbox Code Playgroud)
在这种情况下songs包含列表列表.但是在原始的生成函数中,songs = Repo.all(Song)它是一个Song结构列表.
这意味着模板中的song_path函数会出现以下错误消息: maps cannot be converted to_param. A struct was expected, got: %{artist: "Stephen", id: 3, name: "Crossfire"}
当然,我真正想做的是以某种方式num_votes在select语句中添加一个字段,然后以某种方式为Song结构创建一个相应的字段?
我在RSpec中找到valid_session的例子时遇到了麻烦,现在所有的脚手架测试都在添加授权后被破坏了.
通过Michael Hartl的Rails教程,我正在使用此处描述的身份验证,除了我要求所有页面都登录并使用'skip_before_filter'进行登录等.
我添加了一个用户夹具,我已验证它已加载:
userexample:
id: 1
name: Example Name
email: examplename@example.com
password_digest: $2a$10$NuWL8f2X0bXaCof3/caiiOwlF2rago7hH10JECmw1p75kEpf0mkie
remember_token: YXjPrFfsK8SFQOQDEa90ow
Run Code Online (Sandbox Code Playgroud)
然后在控制器规范中
def valid_session
{ remember_token: "YXjPrFfsK8SFQOQDEa90ow" }
end
Run Code Online (Sandbox Code Playgroud)
会话助手的代码
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user
end
def signed_in?
return !current_user.nil?
end
def sign_out
self.current_user = nil
cookies.delete(:remember_token)
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
end
Run Code Online (Sandbox Code Playgroud)
我是否按预期使用valid_session?提供一个带有会话的remember_token甚至可以在没有使用sign_in明确登录用户的情况下工作吗?这可以通过其他方式解决吗?
我有一个大型项目,我想使用以下命令替换模块名称:
find app/ -type f -exec sed -i '' 's/Foo/Bar/g' {} +
这很好用,但是sed还在所有文件的末尾添加了换行符(即使它找不到任何要替换的Foo).
如何防止sed添加这些换行符?
我在OSX上,使用sed的BSD版本.
(为了记录,我非常同意这里的sed,但我不想污染该项目的git历史.)
使用perl,您可以这样做:
$ perl -pi -e 's/foo/bar/g' *.txt
这将在当前目录中的所有*.txt文件中用"bar"替换字符串"foo".
我喜欢这个,但我想知道使用Ruby是否可以做同样的事情.