我很難理解爲什麼這不起作用。我有一個評論系統,並有一個鏈接來創建一個新的評論,通過2個屬性; user_id和gigid。這兩個id都是作爲整數生成的,但是當我保存評論時,這個gigid保存爲'nil'而不是整數。Rails 4.創建模型時屬性不保存
檢視:
<%= link_to 'Click here to rate this user', new_user_review_path(:user_id => request.user.id, :gigid => request.gig.id) %>
這裏既有ID的正確設置(根據服務器輸出)。 User_id是要被審查的用戶(正常工作),而gigid是後驗證的參考。 (正常工作,直到我試圖保存)
_form:
<%= simple_form_for([@user, @user.reviews.build]) do |f| %>
<div id="rating-form">
<label>Rating</label>
</div>
<%= f.input :comment %>
<%= f.button :submit %>
<% end %>
控制器:
def new
if user_signed_in?
@review = current_user.reviews.new
else
redirect_to(root_url)
flash[:danger] = "You must log in to rate a user"
end
end
def create
@review = @user.reviews.new review_params
@review.reviewed_id = current_user.id
if @review.save
redirect_to user_path(@user)
else
render 'new'
end
end
private
def review_params
params.require(:review).permit(:rating, :comment, :gigid, :user_id)
end
end
服務器輸出,當點擊鏈接:
Started GET "https://stackoverflow.com/users/21/reviews/new?gigid=17&locale=en" for 127.0.0.1 at 2016-01-13 18:08:26 +0100
Processing by ReviewsController#new as HTML
Parameters: {"gigid"=>"17", "locale"=>"en", "user_id"=>"21"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 21]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Rendered reviews/_form.html.erb (4.9ms)
我再添加評論和評級和點擊創建。點擊創建時 服務器輸出:
Started POST "https://stackoverflow.com/users/21/reviews?locale=en" for 127.0.0.1 at 2016-01-13 18:10:44 +0100
Processing by ReviewsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"RToZwvodvXxQp1/spEhgemO/oi+4rof8jREuLw27CcEsEBqFWGLeYne1CgH3kvWu9OzAV+bHvOk9g9nq8JMPnw==", "review"=>{"rating"=>"5", "comment"=>"sdfsdfdd"}, "commit"=>"Create Review", "locale"=>"en", "user_id"=>"21"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 21]]
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.7ms) INSERT INTO "reviews" ("rating", "comment", "user_id", "reviewed_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["rating", 5], ["comment", "sdfsdfdd"], ["user_id", 21], ["reviewed_id", 1], ["created_at", "2016-01-13 17:10:44.675386"], ["updated_at", "2016-01-13 17:10:44.675386"]]
(93.6ms) commit transaction
我注意到,「gigid」被完全忽略了這裏,但一切可以節省的罰款。 我不明白爲什麼一個屬性保存,另一個不存在,任何有識之士將不勝感激!
您能否發佈表單代碼? – Pavan
我正在使用link_to而不是表單。引用代碼的第一位是我正在使用的代碼。 –
哪裏是'#new'行動代碼? –