我有两张表,发电机和结果。
生成器has_many结果 结果belongs_to generator
我怎样才能有一个页面,我可以显示生成器的所有值和结果?在我的Result Controller中,创建必须链接Generator_id吗?我试过但是当我试图创建属于该生成器的新结果时,它会给我一个错误。
例如localhost:3000 / generator / 3 / results / new,点击创建后,它会出现以下错误:
Couldn't find Generator without an ID .
我收到的一些建议要求我创建一个新的控制器。如果是这样,我应该如何将@generator和@result传递给它?
def index
@generators = Generator.all(:include => [:results])
end
def create
@generator = Generator.new(generator_params)
@generator.choice = params[:choice]
if params[:choice] == 'Randomly'
@generator.random_generate(generator_params)
elsif params[:choice] == 'No_of_ATGC'
@generator.no_ATGC(params[:no_A],params[:no_T],params[:no_G],params[:no_C])
elsif params[:choice] == 'Seating'
@generator.seating(params[:user_seq])
end
@generator.result_choice=params[:result_choice]
respond_to do |format|
if @generator.save
if @generator.result_choice == 'Yes'
format.html { redirect_to(new_generator_result_path(@generator)) }
else
format.html { redirect_to @generator, notice: 'Result was successfully created.' }
format.json { render action: 'show', status: :created, location: @generator }
end
else
format.html { render action: 'new' }
format.json { render json: @generator.errors, status: :unprocessable_entity }
end
end
end
class Result < ActiveRecord::Base
attr_accessible :ncbi_ref_seq,:genome_seq, :genome_sample
belongs_to :generator, foreign_key: "generator_id"
def generate_result(result_params)
ref_seq = self.ncbi_ref_seq
Bio::NCBI.default_email = "spykix@hotmail.com"
fasta_sequence = Bio::NCBI::REST::EFetch.nucleotide(ref_seq,"fasta")
fasta=Bio::FastaFormat.new(fasta_sequence)
self.genome_seq = fasta.data
self.genome_sample = fasta.definition
g=Generator.last
p=self.genome_seq.scan(g.c_primer)
self.binding_times= p.length()
end
end
def index
@results = Result.all(:include => :generator)
end
def create
@result = Result.new
@result = @result.generate_result(result_params)
@generator = Generator.find(params[:id])
@result = generator.results.build(result_params)
respond_to do |format|
if @result.save
format.html { redirect_to @result, notice: 'Result was successfully created.' }
format.json { render action: 'show', status: :created, location: @result }
else
format.html { render action: 'new' }
format.json { render json: @result.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
我只想在控制器中创建一个变量:
@generators = Generator.all
然后在你看来......
<% @generators.each do |g| %>
<% g.results.each do |r| %>
<% debug r %>
<% end %>
<% end %>
这听起来就像你用来试图拔出所有发电机的代码一样。
答案 1 :(得分:0)
您正在尝试实施嵌套资源http://guides.rubyonrails.org/routing.html#nested-resources
您需要将路线修改为类似
的路线 resources :generators do
resources :results
end
这样你就拥有了generator_id,所以你可以将你的控制器代码修改为:
generator = Generator.find(params[generator_id])
generator.results.build(result_params)