のためのモデルへのパス属性の値が... Railsの4:私の「エントリ」モデルでダイナミックvailidation
class Entry < ActiveRecord::Base
...私は(下記のデータ検証に直接属性の値を渡すためにしようとしています動的に更新される属性は ':wpu'で、値はユーザーのフォーム提出に基づく整数です。ドロップダウンメニューからの3つのユーザーオプションが ':wpu'の値を送信しますこの会話は、 '5'、 '10'、または '20'のいずれかの値を考慮してください)。
validates :text, length: { is: DYNAMIC_VALUE_WOULD_GO_HERE,
tokenizer: lambda { |str| str.squish.gsub('&'){''}.scan(/\w+/) }
}
これは時に文字列属性のワードカウントを検証「:テキストは」「:WPU」先に述べた他の属性の整数に等しいです。上記のコードは、 'DYNAMIC_VALUE_WOULD_GO_HERE'を '5'、 '10'、または '20'に置き換えても機能しますが、ユーザーの入力に基づいて動的値を配置することに成功していません。
私はこの問題に取り組んできました。おそらく簡単な答えがありました.3日間は成功していません。
私が試してみました物事:
1)attr_readerを使用して属性を呼び出すことが 2値)、私は任意の提案や他の方法に開いていたモデル
にコントローラメソッドのパラメータを渡します。私はルビーとレールの初心者です。
ここに私のフルモデルコードがあります。私は 'params'を通過できなかったので、現在は動作しません。そうでなければ、この動的にしようとすることなく、私は以下のランダムな実験的な方法を削除するとすべて正常に動作します。
class Entry < ActiveRecord::Base
belongs_to :story
attr_reader :wpu
#method used to generate 'wpu' | which is words per user in Story
def self.storywpu
#story ID from EntriesController
current_entry_story_id = Entry.find(params[:id]).story_id
#returns 'wpu' | which is words per user in Story
storywpu = Story.find(current_entry_story_id).wpu
return storywpu
end
#strips ALL white space before form submission
auto_strip_attributes :text, :nullify => false, :squish => true
#validates each field has been filled out
validates :user_id, presence: true
validates :story_id, presence: true
validates :text, presence: true, autocomplete: false
#validates word count is exactly 'wpu' | which is words per user in Story
validates :text, length: { is: self.storywpu,
tokenizer: lambda { |str| str.squish.gsub('&'){''}.scan(/\w+/) }
}
end
そして、ここに参照のための私のコントローラの関連する部分である...
class EntriesController < ApplicationController
before_action :set_entry, only: [:show, :edit, :update, :destroy]
def create
#New text entry
@entry = Entry.create(entry_params)
#Related story params
@story = Story.find(@entry.story_id)
@storyWPU = Story.find(@entry.story_id).wpu
@word_count = @entry.text.squish.gsub('&'){''}.scan(/\w+/).size.to_i
@wordsLeft = @storyWPU - @word_count
if @word_count.nil?
@response = 'enter ' + @wordsLeft.to_s + ' words'
elsif @wordsLeft == 1
@response = 'enter ' + @wordsLeft.to_s + ' word'
elsif @wordsLeft < 0
@response = @wordsLeft.abs.to_s + ' too many!'
else
@response = 'enter ' + @wordsLeft.to_s + ' words'
end
respond_to do |format|
if @entry.save
format.html { redirect_to edit_story_path(@story), notice: 'Nice!' }
format.json { render :show, status: :created, location: @entry }
else
format.html { redirect_to edit_story_path(@story), notice: @response }
format.json { render json: @entry.errors, status: :unprocessable_entity }
end
end
end
private
def set_entry
@entry = Entry.find(params[:id])
end
private
def entry_params
params.require(:entry).permit(:text, :user_id, :story_id, :wpu)
end
end