2016-08-01 2 views
0

:: db를 쿼리하고 결과를 변수에 저장하고 그 결과를 해당 변수별로 뷰에 표시하려고합니다. 결과를 표시하거나 저장하는 방법을 모르겠습니다.레일즈 앱에서 데이터베이스를 쿼리하는 방법은 무엇입니까?

이것을 실행하는 적절한 방법은 무엇입니까?

# MODEL 
class Computer < ActiveRecord::Base 
    has_one :name 
    has_one :used_at 
    has_one :used_for 
    has_one :cash 
end 

CONTROLLER :

class SubmitController < ApplicationController 
    def shoot 
    used_at = params[:where_at] 
    used_for = params[:used_at] 
    cash = params[:amount] 
    #I tried to store the variable. 
    #Is this correct? v 
    search = Computer.find(8) 
    render:shoot 
    end 
    end 

VIEW

다음
       # submit: A controller | shoot: A method 
<%= simple_form_for :computer , url:submit_shoot_path , :method => :get do |f| %> 

     <%= f.input :used_at, collection: ["Home" , "Work" , "Travel"] , wrapper_html: { class: 'col-xs-3'} %> 
     <%= f.input :used_for, collection: [ "Programming", "Gaming", "Blogging"], wrapper_html: { class: 'col-xs-3'} %> 
     <br/> 
     <%= f.input :cash, input_html: { max: 500 } , wrapper_html: { class: 'col-xs-3' } %> 
     <br/> 
     <%= f.button :submit, value: 'Submit' , :name => nil %> 
    <% end %> 

내 모델의 :

이 양식입니다 (첫 페이지) : 여기

코드입니다 : 나는 쿼리에 의해 영향을받은 모든 행을 나열 할 (예 : 찾을 수 * 가격 = '400'컴퓨터) 그리고 결과이 같은 것입니다 :

이름 :. 도시바 (명) | 가격 : $ 1.00 (현금) | 집 (중고차) | 프로그래밍 (used_for).

이 페이지는 오류없이 표시됩니다. 로드되지만 쿼리 결과를로드하는 방법은 무엇입니까? 결과 (두 번째 페이지) : shoot.html.erb

** 지금보기 안에 내가 ** 목록 (리)에서 DB 쿼리의 결과를 나열 할

<html> 
<head>Hello</head> 

<body> 
<table> 
    <ul> 
     <!-- Isn't there a search.each do |t| method that goes here. --> 
    </ul> 
</table> 
</body> 
</html> 

하시기 바랍니다, SOF 루비스트가이 문제를 해결할 수 있도록 도와달라고 부탁합니다.

참고 : guides.rubyonrails.org에 대한 권장 사항이 없습니다. 당신의 SubmitController.rb보기 파일에 다음

@search = Computer.find(8) ## @search is a instance variable now. You can use it in views. @Search contains a record from computer whose id is 8. 

에서

답변

0

,

<%= @search.name %> ## i assume name is a column in computers method. 
<%= @search.xyz %> ## xyz is again a column name and so on... 

당신이 SubmitControoler.rb에서 작성하는 경우 다음

@search = Computer.all ## fetch all the records from computers tables. 

그것은 개체의 컬렉션을 가져옵니다 컴퓨터 수업. 다음과 같이보기에서 반복 할 수 있습니다.

<% @search.each do |x| %> 
    <%= x.name %> 
    <%= x.xyz %> 
    ...... 
<% end %> 
+0

고마워요! 그러나 "각 메서드가 정의되지 않았습니다."라는 오류가 발생했습니다. 이 문제를 어떻게 해결할 수 있습니까? –

+0

컨트롤러 방법과 존중 된보기에 대한 코드를 공유하십시오. –

+1

나는 그것을 고쳤다. @ 검색을 @ computers (복수형)로 변경했습니다. 그리고 '컴퓨터'모델에서 used_at, where_at를 UsedAt 및 WhereAt로 변경했습니다. –

관련 문제