rails button_不传递params hash中的ID



当单击按钮使用按钮使用Twitter Gem并将其存储在我的数据库中时,我正在尝试调用方法。

我有一个称为赞助商的模型(其中包括一个存储Twitter用户名的列)和一个称为赞助的模型:

型号/赞助商:

class Sponsor < ActiveRecord::Base                                                      
  attr_accessible :facebook, :name, :twitter                                         
  has_many :sponsortweets, dependent: :destroy                                          
                                                                                          validates :name, presence: true, uniqueness: { case_sensitive: false }                
  VALID_TWITTER_REGEX = /A^([a-zA-Z](_?[a-zA-Z0-9]+)*_?|_([a-zA-Z0-9]+_?)*)$/          
  validates :twitter, format: { with: VALID_TWITTER_REGEX },                            
                      uniqueness: { case_sensitive: false }                             

  def create_tweet                                                                      
    tweet = Twitter.user_timeline(self.twitter).first                                   
    self.sponsortweets.create!(content: tweet.text,                                     
                               tweet_id: tweet.id,                                      
                               tweet_created_at: tweet.created_at,                      
                               profile_image_url: tweet.user.profile_image_url,         
                               from_user: tweet.from_user,)                             
  end                                                                                   
end

型号/赞助网:

class Sponsortweet < ActiveRecord::Base
  attr_accessible :content, :from_user, :profile_image_url, :tweet_created_at, :tweet_id
    belongs_to :sponsor
    validates :content, presence: true
    validates :sponsor_id, presence: true
    default_scope order: 'sponsortweets.created_at DESC'
end

在控制器/sponsors_controller.rb中:

def tweet
        @sponsor = Sponsor.find_by_id(params[:id])
        @sponsor.create_tweet
    end

我的路由中的相关行:

match 'tweet', to: 'sponsors#tweet', via: :post

在我的视图中(视图/赞助商/show.html.haml):

= button_to :tweet, tweet_path

使用此代码,单击按钮时会遇到以下错误: undefined method create_tweet'for nil:nilclass`

如果我更改使用查找(而不是find_by_id),则错误是: Couldn't find Sponsor without an ID

...这让我认为据我所知,使用ID不会通过,而Find_by_id返回nil。

我应该更改如何使ID通过?

您需要使用路径助手的id参数:

= button_to :tweet, tweet_path(:id => @sponsor.id)

如果您不希望在查询字符串中:

= form_tag tweet_path do |f|
  = hidden_field_tag :id => @sponsor.id
  = submit_tag "Tweet"

这与您的button_to一样,但在生成的表单中添加一个隐藏的字段。

最新更新