我尝试使用where返回特定主题ID在ruby中的课程。在控制台中,它会提供我想要的正确ID,但它会返回许多ID错误的课程。谁能告诉我我的代码有什么问题吗?谢谢!
def display
subject_id = search_params[:subject]
puts subject_id
@courses = Course.where("subject_id", subject_id)
puts @courses.inspect
@courses = @courses.where("name LIKE ?", search_params[:course])
puts "******"
puts @courses.inspect
puts "******"
end
这就是控制台中显示的内容
Started POST "/search" for 127.0.0.1 at 2018-10-20 18:22:41 -0400
Processing by UsersController#display as JS
Parameters: {"utf8"=>"✓", "subject"=>"1161-850", "course"=>"", "commit"=>"Search"}
Unpermitted parameters: :utf8, :commit
1161-850
Course Load (0.2ms) SELECT "courses".* FROM "courses" WHERE (subject_id) LIMIT ? [["LIMIT", 11]]
Unpermitted parameters: :utf8, :commit
******
Course Load (0.4ms) SELECT "courses".* FROM "courses" WHERE (subject_id) AND (name LIKE '') LIMIT ? [["LIMIT", 11]]
#<ActiveRecord::Relation []>
******
Rendering users/display.html.erb within layouts/application
Course Load (0.4ms) SELECT "courses".* FROM "courses" WHERE (subject_id) AND (name LIKE '')
Rendered users/display.html.erb within layouts/application (1.8ms)
Rendered layouts/_shim.html.erb (0.5ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendered layouts/_header.html.erb (2.0ms)
Rendered layouts/_footer.html.erb (0.9ms)
答案 0 :(得分:2)
Course.where("subject_id", subject_id)
并没有达到您的期望。它会生成一个带有字符串"subject_id"
的条件,并会传递subject_id
的值作为该条件的参数,前提是条件中有一个?
。
只用写这个
Course.where(subject_id: subject_id)
我建议阅读有关ActiveRecord Query interface in the Rails Guides的信息。
此外,几行后的LIKE
查询也不起作用。您可能要看看这个question about generating like queries in ActiveRecord。
答案 1 :(得分:0)
如果要查找具有特定subject_id和课程名称的课程,则可以在一个查询中完成:
$options = array(
'fields' => array(
'shops.phone1',
),
'joins' => array(
array(
),
),
'conditions' => array(
'Gallery.album_id = albums.id',
'albums.shop_id = shops.id',
'Gallery.id' => '210',
),
);
$data = $this->find('all', $options);