我有3个模型,分别是source,twitter_source和twitter_aggregation_method模型。
他们的关系设置如下:
sources.rb
has_many :twitter_sources
twitter_sources.rb
has_one :twitter_aggregation_method
belongs_to :source
twitter_aggregation_method.rb
belongs_to :twitter_source
当我尝试创建一个新的twitter_aggregation_method时,我收到以下错误:
NoMethodError in TwitterAggregationMethodsController#create
undefined method `twitter_source' for #<Source:0xb331fa20>
我的 twitter_aggregation_methods_controller.rb 设置如下:
class TwitterAggregationMethodsController < ApplicationController
before_action :set_twitter_aggregation_method, only: [:show, :edit, :update, :destroy]
before_filter :get_twitter_source, :get_source
def index
@twitter_aggregation_methods = @twitter_source.twitter_aggregation_method
end
def show
@twitter_aggregation_method = @twitter_source.twitter_aggregation_methods.find(params[:id])
end
def new
@twitter_aggregation_method = TwitterAggregationMethod.new
end
def edit
end
def create
source = @source
twitter_source = @twitter_source
@twitter_aggregation_method = source.twitter_source.twitter_aggregation_method.new(twitter_aggregation_method_params)
respond_to do |format|
if @twitter_aggregation_method.save
format.html { redirect_to [@twitter_source, @twitter_aggregation_method], notice: 'Twitter aggregation method was successfully created.' }
format.json { render action: 'show', status: :created, location: [@twitter_source, @twitter_aggregation_method]}
else
format.html { render action: 'new' }
format.json { render json: @twitter_aggregation_method.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @twitter_aggregation_method.update(twitter_aggregation_method_params)
format.html { redirect_to [@twitter_source, @twitter_aggregation_method], notice: 'Twitter aggregation method was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @twitter_aggregation_method.errors, status: :unprocessable_entity }
end
end
end
def destroy
@twitter_aggregation_method.destroy
respond_to do |format|
format.html { redirect_to twitter_aggregation_methods_url }
format.json { head :no_content }
end
end
def get_source
@source = Source.find(params[:source_id])
end
def get_twitter_source
@twitter_source = TwitterSource.find(params[:twitter_source_id])
end
private
def set_twitter_aggregation_method
@twitter_aggregation_method = TwitterAggregationMethod.find(params[:id])
end
def twitter_aggregation_method_params
params.require(:twitter_aggregation_method).permit(:twitter_source_id, :tweets, :retweets, :favourites)
end
end
我的 routes.rb 如下:
resources :sources do
resources :rss_sources
resources :twitter_sources do
resources :twitter_aggregation_methods
resources :influencer_trends do
resources :trends
end
end
end
答案 0 :(得分:0)
我认为您打算使用source.twitter_sources
而不是source.twitter_source