0

私はattr_accessor :politics, :tech, :entertainment, :sports, :science, :crime, :business, :social, :nature, :otherpost.rb(これらはタグです)にあり、それらを仮想にしたいです。

次に、 new.html.erb に

<%= f.check_box :politics %>
<%= f.label :politics %>

<%= f.check_box :tech %>
<%= f.label :tech, 'Technology' %>

<%= f.check_box :entertainment %>
<%= f.label :entertainment %>

<%= f.check_box :sports %>
<%= f.label :sports %>

<%= f.check_box :science %>
<%= f.label :science %>

<%= f.check_box :crime %>
<%= f.label :crime %>

<%= f.check_box :business %>
<%= f.label :business %>

<%= f.check_box :social %>
<%= f.label :social %>

<%= f.check_box :nature %>
<%= f.label :nature %>

<%= f.check_box :other %>
<%= f.label :other %>

それぞれが true または false として設定されるように、最後に、post_controller.rb の下def createにある

@post.tag_list << 'politics' if :politics
@post.tag_list << 'tech' if :tech
@post.tag_list << 'entertainment' if :entertainment
@post.tag_list << 'sports' if :sports
@post.tag_list << 'science' if :science
@post.tag_list << 'crime' if :crime
@post.tag_list << 'business' if :business
@post.tag_list << 'social' if :social
@post.tag_list << 'nature' if :nature
@post.tag_list << 'other' if :other

ただし、コンソールでpost.tag_listを実行すると、すべてのタグの応答が得られます#=>'politics, tech, ... nature, other'

チェックしないと :business = false にならないのはなぜですか?

4

1 に答える 1

1

コントローラーは次のようになります。

@post.tag_list.clear
@post.tag_list << 'politics' if params[:post][:politics]
@post.tag_list << 'tech' if params[:post][:tech]
@post.tag_list << 'entertainment' if params[:post][:entertainment]
@post.tag_list << 'sports' if params[:post][:sports]
@post.tag_list << 'science' if params[:post][:science]
@post.tag_list << 'crime' if params[:post][:crime]
@post.tag_list << 'business' if params[:post][:business]
@post.tag_list << 'social' if params[:post][:social]
@post.tag_list << 'nature' if params[:post][:nature]
@post.tag_list << 'other' if params[:post][:other]

シンボル自体は常に true と評価されます。変数というより定数のようなものです。したがって、値が割り当てられることはありません。

于 2011-07-16T06:25:13.290 に答える